Skip to main content

Full text of "HTML Book"

See other formats


100°/< 

imiiimumm 

COMPREHENSIVE 
AUTHORITATIVE 
WHAT YOU NEED 

m 

Construct tutting- 
edge Web sites and 
learn effective ways 
to keep them fresh 

Build 

knowledge of the 
latest enhancements 
to these tore Web 
technologies 




Save time using only 
the mast practical 
and proven tools 
and techniques 



COMPANION 


■W ^LW .^ W . ^«F M «V ~~ "A 


WEB SITE 


3rd Edition 


Iridudes code for down loading, 


Bryan Pfaffenberger, Steven H. Schofer, Chuck White, 


bonus appendixes, and more 


k^ and Bill Karow 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



HTML, XHTML, 

and CSS Bible 



3rd Edition 



Brian Pfaffenberger, Steven M. Schafer, 
Charles White, Bill Karow 



® 



WILEY 

Wiley Publishing, Inc. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



HTML, XHTML, 

and CSS Bible 



3rd Edition 



Brian Pfaffenberger, Steven M. Schafer, 
Charles White, Bill Karow 



® 



WILEY 

Wiley Publishing, Inc. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



HTML, XHTML, and CSS Bible, 3rd Edition 

Published by 

Wiley Publishing, Inc. 

10475 Crosspoint Boulevard 
Indianapolis, IN 46256 

www. wi 1 ey . com 

Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana 

Published simultaneously in Canada 

elSBN: 0-7645-7718-2 

Manufactured in the United States of America 

10 98765 432 1 

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form 
or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as 
permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior 
written permission of the Publisher, or authorization through payment of the appropriate per-copy fee 
to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 
646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley 
Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, 
e-Mail: brandrevi ew@wi 1 ey . com. 



LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE 



NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETE- 
NESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, 
INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. 
NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. 
THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SIT- 
UATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT 
ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF 
PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL 
PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE 
FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEB SITE IS 
REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER 
INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE 
INFORMATION THE ORGANIZATION OR WEB SITE MAY PROVIDE OR RECOMMENDATIONS IT 
MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEB SITES LISTED 
IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS 
WRITTEN AND WHEN IT IS READ. 



For general information on our other products and services or to obtain technical support, please 
contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 
572-3993 or fax (317) 572-4002. 

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may 
not be available in electronic books. 

Library of Congress Cataloging-in-Publication Data: Available from Publisher 

Trademarks: Wiley, the Wiley logo, and related trade dress are trademarks or registered trademarks of 
John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be 
used without written permission. All other trademarks are the property of their respective owners. 
Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. 



is a trademark of Wiley Publishing, Inc. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



About the Authors 



Bryan Pfaffenberger is the author of more than 75 books on computers and the 
Internet, including the best-selling Discover the Internet, from IDG Books Worldwide. 
He teaches advanced professional communication and the sociology of computing in 
the University of Virginia's Division of Technology, Culture, and Communication. 
Bryan lives in Charlottesville, Virginia, with his family and an extremely spoiled cat. 

Steven M. Schafer is a veteran of technology and publishing. He programs in several 
languages, works with a variety of technologies, and has been published in several 
technical publications and articles. He currently is the COO/CTO for Progeny, an 
open source-based service and support company. Steve can be reached by e-mail at 

sschaf er@synergy-tech .com. 

Chuck White is a Web development professional who has written numerous articles 
and books on Web development, including Mastering XSLT and Developing Killer Web 
Apps with Dreamweaver MX and C#, and tutorials for IBM DeveloperWorks. His first 
published work on CSS was for Web Techniques magazine in 1997, and he has been 
working with large and small Web sites since 1996. He is currently a Web software 
engineer for eBay. 

Bill Karow, in addition to writing several computer books, has served as a 
contributor or technical editor on more than 30 other books. Formerly in charge of 
systems development for Walt Disney Entertainment, Bill now serves as a computer 
consultant in the Orlando area when he's not out riding his bicycle. He also has the 
distinction of having stood atop many of the buildings at Walt Disney World, fanfare 
trumpet in hand (with their permission, of course). 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Credits 



Acquisitions Editor 

Jim Minatel 

Development Editor 

Marcia Ellett 

Production Editor 

Gabrielle Nabi 

Technical Editor 

Wiley-Dreamtech India Pvt Ltd 

Copy Editor 

TechBooks 

Editorial Manager 

Mary Beth Wakefield 



Vice President & Executive 
Group Publisher 

Richard Swadley 

Vice President and Executive 
Publisher 

Bob Ipsen 

Vice President and Publisher 

Joseph B. Wikert 

Executive Editorial Director 

Mary Bednarek 

Project Coordinator 

Erin Smith 

Proofreading and Indexing 

TechBooks Production Services 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



To Miri, I'll desperately miss 

my late-night company. 

Steve 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Acknowledgments 



A book such as this is hard work, and only a small portion of that work is 
performed by the authors. As such, the authors would like to thank 
the following: 

The management team at Wiley Publishing for continuing to support large, tutorial- 
reference books so folks like you (the reader) can benefit. 

Jim Minatel, for putting together the plan, assembling the team, and making us all 
behave. 

Bryan Pfaffenberger, the original author of the 1 st and 2 nd Editions of this book, for 
providing a solid outline and organization for us to follow. 

John Daily, who compiled the referential information in Appendixes A and B, for 
stepping up and providing the critical attention to detail necessary for such work. 

Marcia Ellett, for continuing to be one of the best development editors around — 
keeping us all on track and organized — and for providing crucial insights and 
feedback throughout the process. 

Wiley-Dreamtech India Pvt Ltd. for providing the technical editing — ensuring that the 
information is accurate and pertinent, as well as providing additional useful insights. 

TechBooks, for ensuring that our text is easy to read and understand, despite our 
best efforts. 

The production crew who packaged the raw material into this nice package you 
now hold. 

And last, but definitely not least, our friends and family who give us the love and 
support that enables us to do this in the first place. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents at a Glance 



Acknowledgments iv 

Introduction xxiii 

Part I: Understanding (X)HTML 1 

Chapter 1: Introducing the Web and HTML 3 

Chapter 2: What Goes Into a Web Page? 19 

Chapter 3: Starting Your Web Page 43 

Part II: HTML/XHTML Authoring Fundamentals 53 

Chapter 4: Lines, Line Breaks, and Paragraphs 55 

Chapter 5: Lists 75 

Chapter 6: Images 91 

Chapter 7: Links 113 

Chapter 8: Text 127 

Chapter 9: Special Characters 135 

Chapter 10: Tables 149 

Chapter 1 1 : Page Layout with Tables 1 73 

Chapter 12: Frames 189 

Chapter 13: Forms 205 

Chapter 14: Multimedia 227 

Chapter 15: Scripts 257 

Part III: Controlling Presentation with CSS 267 

Chapter 16: Introducing Cascading Style Sheets 269 

Chapter 17: Creating Style Rules 279 

Chapter 18: Fonts 297 

Chapter 19: Text Formatting 313 

Chapter 20: Padding, Margins, and Borders 337 

Chapter 2 1 : Colors and Backgrounds 347 

Chapter 22: Tables 359 

Chapter 23: Element Positioning 369 

Chapter 24: Defining Pages for Printing 387 

Part IV: Advanced Web Authoring 399 

Chapter 25: JavaScript 401 

Chapter 26: Dynamic DHTML 429 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



y\\\ Contents at a Glance 



Chapter 27: Dynamic HTML with CSS 449 

Chapter 28: Introduction to Server-Side Scripting 469 

Chapter 29: Introduction to Database-Driven Web Publishing 479 

Chapter 30: Creating a Weblog 495 

Chapter 31 : Introduction to XML 505 

Chapter 32: XML Processing and Implementations 523 

Part V: Testing, Publishing, and Maintaining Your Site 547 

Chapter 33: Testing and Validating Your Documents 549 

Chapter 34: Web Development Software 555 

Chapter 35: Choosing a Service Provider 567 

Chapter 36: Uploading Your Site with FTP 575 

Chapter 37: Publicizing Your Site and Building Your Audience 583 

Chapter 38: Maintaining Your Site 591 

Part VI: Principles of Professional Web Design 

and Development 601 

Chapter 39: The Web Development Process 603 

Chapter 40: Developing and Structuring Content 617 

Chapter 41 : Designing for Usability and Accessibility 629 

Chapter 42: Designing for an International Audience 645 

Chapter 43: Security 659 

Chapter 44: Privacy 667 

Part VII: Appendixes 677 

Appendix A: HTML 4.01 Elements 679 

Appendix B: CSS Properties 743 

Index 773 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents 

Acknowledgments iv 

Introduction xxiii 



Part I: Understanding OOHTML 



Chapter 1 : Introducing the Web and HTML 3 

What Is the World Wide Web? 3 

How Does the Web Work? 3 

What Is Hypertext? 4 

Where Does HTML Fit In? 5 

The invention of HTML 5 

A short history of HTML 6 

So who makes the rules? 8 

What Is CSS? 10 

The maintenance nightmare 10 

Enter CSS 13 

What does "cascading" mean? 14 

What Is XHTML? 15 

Creating an HTML Document 15 

Writing HTML 16 

Name your files with a Web-friendly extension 16 

Format your text 16 

Structure your document 16 

Don't I Need a Web Server? 17 

Summary 18 

Chapter 2: What Goes Into a Web Page? 19 

Specifying Document Type 19 

The Overall Structure: HTML, Head, and Body 20 

The <html> tag 20 

The <head> tag 20 

Styles 22 

Block Elements: Markup for Paragraphs 24 

Formatted paragraphs 25 

Headings 26 

Quoted text 27 

List elements 28 

Preformatted text 30 

Divisions 30 

Inline Elements: Markup for Characters 31 

Basic inline tags 31 

Spanning 32 

Special Characters (Entities) 32 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents 



Organizational Elements 33 

Tables 34 

Forms 36 

Linking to Other Pages 37 

Images 38 

Comments 39 

Scripts 40 

Putting it All Together 40 

Summary 41 

Chapter 3: Starting Your Web Page 43 

Basic Rules for HTML Code 43 

Use liberal white space 43 

Use well-formed HTML 44 

Comment your code 45 

Creating the Basic Structure 46 

Declaring the Document Type 46 

Specifying the Document Title 47 

Providing Information to Search Engines 48 

Setting the Default Path 49 

Creating Automatic Refreshes and Redirects 49 

Page Background Color and Background Images 50 

Specifying the document background color 50 

Specifying the document background image 51 

Summary 52 



Part II: HTML/XHTML Authoring Fundamentals 



Chapter 4: Lines, Line Breaks, and Paragraphs 55 

Line Breaks 55 

Paragraphs 56 

Manual line breaks 59 

Nonbreaking Spaces 60 

Soft Hyphens 61 

Preserving Formatting — The <pre> Element 63 

Indents 64 

Headings 66 

Horizontal Rules 68 

Grouping with the <div> Element 70 

Summary 73 

Chapter 5: Lists 75 

Understanding Lists 75 

Ordered (Numbered) Lists 76 

Unordered (Bulleted) Lists 82 

Definition Lists 86 

Nested Lists 87 

Summary 89 

Chapter 6: Images 91 

Image Formats for the Web 91 

Image compression 91 

Compression options 91 

Image color depth 93 

Enhancing downloading speed 94 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents )(j 



Creating Graphics 95 

Essential functions 95 

Free alternatives 96 

Progressive JPEGs and interlaced GIFs 97 

Inserting an Image 99 

Image Alignment 100 

Specifying Text to Display for Nongraphical Browsers 102 

Size and Scaling 103 

Image Borders 105 

Image Maps 106 

Specifying an image map 107 

Specifying clickable regions 107 

Putting it all together 109 

Animated Images 110 

Summary Ill 

Chapter 7: Links 113 

What's in a Link? 113 

Linking to a Web Page 115 

Absolute versus Relative Links 116 

Link Targets 117 

Link Titles 119 

Keyboard Shortcuts and Tab Order 119 

Keyboard shortcuts 120 

Tab order 120 

Creating an Anchor 121 

Choosing Link Colors 121 

Link Target Details 123 

The Link Tag 125 

Summary 125 

Chapter 8: Text 127 

Methods of Text Control 127 

The <font> tag 127 

Emphasis and other text tags 128 

CSS text control 128 

Bold and Italic Text 130 

Monospace (Typewriter) Fonts 131 

Superscripts and Subscripts 132 

Abbreviations 132 

Marking Editorial Insertions and Deletions 133 

Grouping Inline Elements with the <span> Tag 134 

Summary 134 

Chapter 9: Special Characters 1 35 

Understanding Character Encodings 135 

Special Characters 136 

En and Em Spaces and Dashes 137 

Copyright and Trademark Symbols 138 

Currency Symbols 138 

"Real" Quotation Marks 139 

Arrows 140 

Accented Characters 140 

Greek and Mathematical Characters 142 

Other Useful Entities 146 

Summary 148 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



XJj Contents 



Chapter 10: Tables 1 49 

Parts of an HTML Table 149 

Table Width and Alignment 151 

Cell Spacing and Padding 153 

Borders and Rules 155 

Table borders 155 

Table rules 157 

Rows 157 

Cells 159 

Table Captions 160 

Row Groupings — Header, Body, and Footer 163 

Background Colors 165 

Spanning Columns and Rows 166 

Grouping Columns 169 

Summary 171 

Chapter 1 1 : Page Layout with Tables 173 

Rudimentary Formatting with Tables 1 73 

Real-World Examples 177 

Floating Page 1 79 

Odd Graphic and Text Combinations 182 

Navigational Menus and Blocks 185 

Multiple Columns 187 

Summary 188 

Chapter 12: Frames 1 89 

Frames Overview 189 

Framesets and Frame Documents 191 

Creating a frameset 191 

Frame margins, borders, and scroll bars 194 

Permitting or prohibiting user modifications 196 

Targeting Links to Frames 196 

Nested Framesets 200 

Inline Frames 201 

Summary 204 

Chapter 13: Forms 205 

Understanding Forms 205 

Inserting a Form 208 

HTTP GET 208 

HTTP POST 209 

Additional <form> attributes 209 

Field Labels 210 

Text Input Boxes 210 

Password Input Boxes 210 

Radio Buttons 211 

Check Boxes 211 

List Boxes 212 

Large Text Areas 214 

Hidden Fields 215 

Buttons 216 

Images 217 

File Fields 217 

Submit and Reset Buttons 218 

Tab Order and Keyboard Shortcuts 219 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents 



XIII 



Preventing Changes 219 

Fieldsets and Legends 221 

Form Scripts and Script Services 222 

Download a handler 224 

Use a script service 224 

Summary 225 

Chapter 14: Multimedia 227 

Introducing Multimedia Objects 227 

Your multimedia options 228 

Including multimedia in your Web pages 229 

Multimedia Plug-Ins and Players 233 

Flash 234 

RealOne 234 

Windows Media Player 234 

QuickTime 235 

Animations 236 

Creating animated GIFs 236 

Keeping files sizes small 236 

Creating a Flash file 239 

Video Clips 240 

Sounds 241 

Slide Shows 242 

Exporting PowerPoint presentations to the Web 242 

Exporting OpenOffice.org presentations 250 

SMIL 251 

Summary 256 

Chapter 15: Scripts 257 

Client-Side versus Server-Side Scripting 257 

Client-side scripting 257 

Server-side scripting 257 

Setting the Default Scripting Language 258 

Including a Script 259 

Calling an External Script 259 

Triggering Scripts with Events 260 

Hiding Scripts from Older Browsers 264 

Summary 265 



Part III: Controlling Presentation with CSS 



Chapter 16: Introducing Cascading Style Sheets 269 

CSS Overview 269 

Style Rules 270 

Style Rule Locations 271 

Using the <style> element 271 

External style sheets 271 

Style definitions within individual tags 272 

Understanding the Style Sheet Cascade 272 

The CSS Box Formatting Model 274 

Box dimensions 274 

Padding 275 

Border 276 

Margins 277 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



XJy Contents 



CSS Levels 1, 2, and 3 277 

Summary 278 

Chapter 17: Creating Style Rules 279 

Understanding Selectors 279 

Matching elements by name 280 

Using the universal selector 280 

Matching elements by class 280 

Matching elements by identifier 281 

Matching elements that contain a specified attribute 281 

Matching child, descendent, and adjacent 

sibling elements 282 

Understanding Inheritance 284 

Pseudo-classes 285 

Defining link styles 285 

The :first-child pseudo-class 286 

The :lang pseudo-class 286 

Pseudo-elements 287 

Applying styles to the first line of an element 287 

Applying styles to the first letter of an element 288 

Specifying before and after text 289 

Shorthand Expressions 291 

Property Value Metrics 293 

Summary 295 

Chapter 18: Fonts 297 

Web Typography Basics 297 

The wrong way to describe fonts 298 

The right way to describe fonts 301 

Working with Font Styling Attributes 303 

Naming font families using CSS 303 

Understanding font families 304 

Understanding fonts and font availability 305 

Working with font styles 305 

Establishing font sizes 306 

Using (or not using) font variants 307 

Bolding fonts by changing font weight 307 

Making font wider or thinner using font stretch 308 

Line height and leading 308 

Downloading Fonts Automatically 308 

Dynamic font standards and options 308 

Licensing issues 309 

Should you use font embedding or style sheets? 309 

How to add downloadable fonts to a Web page 310 

Syntax 310 

Summary 310 

Chapter 19: Text Formatting 313 

Aligning Text 313 

Controlling horizontal alignment 313 

Controlling vertical alignment 316 

Indenting Text 318 

Controlling White Space within Text 319 

Clearing floating objects 319 

The white-space property 320 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents 



Controlling Letter and Word Spacing 322 

Specifying Capitalization 324 

Using Text Decorations 325 

Formatting Lists 326 

An overview of lists 326 

CSS lists — any element will do 327 

List style type 328 

Positioning of markers 330 

Images as list markers 330 

Auto-generated Text 331 

Specifying quotation marks 331 

Numbering elements automatically 332 

Summary 336 

Chapter 20: Padding, Margins, and Borders 337 

Understanding the Box Formatting Model 337 

Denning Element Margins 339 

Adding Padding within an Element 341 

Adding Borders 341 

Border style 341 

Border color 343 

Border width 343 

The ultimate shortcut: The border property 344 

Additional border properties 344 

Using Dynamic Outlines 345 

Summary 346 

Chapter 21 : Colors and Backgrounds 347 

Foreground Color 347 

Background Color 348 

Sizing an Element's Background 348 

Background Images 349 

Repeating and Scrolling Background Images 351 

Positioning Background Images 355 

Summary 358 

Chapter 22: Tables 359 

Defining Table Styles 359 

Controlling Table Attributes 360 

Table borders 360 

Table border spacing 362 

Collapsing borders 363 

Borders on empty cells 363 

Table Layout 364 

Aligning and Positioning Captions 365 

Summary 367 

Chapter 23: Element Positioning 369 

Understanding Element Positioning 369 

Static positioning 369 

Relative positioning 370 

Absolute positioning 371 

Fixed positioning 373 

Specifying Element Position 374 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



XVI 



Contents 



Floating Elements to the Left or Right 377 

Denning an Element's Width and Height 378 

Specifying exact sizes 378 

Specifying maximum and minimum sizes 379 

Controlling element overflow 379 

Stacking Elements in Layers 381 

Controlling Element Visibility 384 

Summary 385 

Chapter 24: Defining Pages for Printing 387 

The Page Box Formatting Model 387 

Denning the Page Size with the ©page Rule 389 

Setting up the page size with the size property 390 

Setting margins with the margin property 390 

Controlling Page Breaks 391 

Using the Page-Break Properties 392 

Using the page-break-before and page-break-after properties 392 

Using the page-break-inside property 396 

Handling Widows and Orphans 396 

Preparing Documents for Double-Sided Printing 398 

Summary 398 



Part IV: Advanced Web Authoring 



Chapter 25: JavaScript 401 

JavaScript Background 40 1 

Writing JavaScript Code 403 

Data types and variables 403 

Calculations and operators 404 

Handling strings 405 

Control structures 405 

Functions 408 

Using objects 409 

Event Handling in JavaScript 410 

Using JavaScript in HTML Documents 412 

Adding scripts with the script element 412 

JavaScript execution 413 

Practical Examples 414 

Browser identification and conformance 414 

Last modification date 416 

Rollover images 416 

Caching images 418 

Form validation 419 

Specifying window size and location 423 

Frames and frameset control 425 

Using cookies 425 

Summary 42 7 

Chapter 26: Dynamic DHTML 429 

The Need for DHTML 429 

How DHTML Works 429 

DHTML and the Document Object Model 430 

Using event handlers 430 

It's all about objects 43 1 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents XVII 



Cross-Browser Compatibility Issues 432 

Browser detection 432 

Object detection 434 

DHTML Examples 434 

Breadcrumbs (page location indicator) 434 

Rollovers 439 

Collapsible menus 445 

Summary 446 

Chapter 27: Dynamic HTML with CSS 449 

DHTML and CSS Properties 452 

Setting CSS properties using JavaScript 453 

Using behaviors to create DHTML effects 456 

Internet Explorer Filters 457 

Filters 458 

Valid HTML filter elements 458 

Visual filters 459 

Summary 467 

Chapter 28: Introduction to Server-side Scripting 469 

How Web Servers Work 469 

Market-Leading Web Servers 471 

Apache 471 

IIS 472 

The Need for Server-Side Scripting 472 

Server-Side Scripting Languages 473 

Common Gateway Interface 473 

ASP, .NET, and Microsoft's technologies 474 

PHP 476 

ColdFusion 477 

Summary 477 

Chapter 29: Introduction to Database-driven Web Publishing 479 

Understanding the Need for Database Publishing 479 

How Database Integration Works 480 

Options for Database Publishing 480 

Pre-generated content 481 

On-demand content 481 

Database Publishing Case Study — A Newsletter 482 

The manual method 482 

The database method 482 

Authentication and Security 491 

Summary 493 

Chapter 30: Creating a Weblog 495 

The Blog Phenomenon 495 

Blog Providers and Software 496 

Userland Software 497 

Movable Type 497 

Blosxom 498 

Posting Content to Your Blog 498 

Handling Comments 499 

Using Permalinks 499 

Using Trackbacks 500 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



XVI 11 Contents 



Syndicating Content with RSS 50 1 

RSS syntax 502 

Publishing the feed 502 

Building an Audience 503 

Summary 504 

Chapter 31 : Introduction to XML 505 

The Need for XML 506 

Relationship of XML, SGML, and HTML 507 

How XML Works 508 

Getting started with XML parsers 508 

Begin with a prolog 509 

Understanding encoding 509 

Well-structured XML 510 

Document Type Definitions 513 

Using elements in DTDs 515 

Using attributes in DTDs 518 

Using entities in DTDs 518 

Using PCDATA and CDATA in DTDs 519 

XML Schemas 519 

Working with Schemas 519 

XML on the Web 522 

Summary 522 

Chapter 32: XML Processing and Implementations 523 

Processing XML 523 

XPath 523 

Style sheets for XML: XSLT 530 

XML Implementations 543 

XHTML 543 

Web services (SOAP, UDDI, and so on) 545 

XUL 545 

WML 545 

Summary 546 



Part V: Testing, Publishing, and Maintaining 
Your Site 



Chapter 33: Testing and Validating Your Documents 549 

Testing with a Variety of Browsers 549 

Testing for a Variety of Displays 550 

Validating Your Code 550 

Specifying the correct document type definition 550 

Validation tools 55 1 

Understanding validation output 552 

Summary 553 

Chapter 34: Web Development Software 555 

Text-Oriented Editors 555 

Simple text editors 555 

Smart text editors 556 

HTML-specific editors 557 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents XIX 



WYSIWYG HTML Editors 558 

Microsoft FrontPage 558 

NetObjects Fusion 560 

Macromedia Dreamweaver 560 

Other Tools 561 

Graphic editors 561 

Macromedia Flash 565 

Summary 565 

Chapter 35: Choosing a Service Provider 567 

Types of Service Providers 567 

Web publishing services provided by ISPs 568 

Using shared hosting services 568 

Using dedicated hosting 568 

Using co-location services 569 

Estimating Your Costs 569 

Support and Service 569 

Bandwidth and Scalability 571 

Contracts 571 

Domain Names 571 

Summary 572 

Chapter 36: Uploading Your Site with FTP 575 

Introducing FTP 575 

FTP Clients 576 

Notable FTP Clients 578 

Principles of Web Server File Organization 580 

Summary 581 

Chapter 37: Publicizing Your Site and Building 

Your Audience 583 

Soliciting Links 583 

Using link exchanges 584 

Newsgroups 584 

Listing Your Site with Search Engines 584 

Facilitating Search Engine Access 585 

Getting links from other sites 585 

Encouraging bookmarks 586 

Keeping your site current 586 

Predicting users' search keywords and enhancing search retrieval 586 

Strategies for Retaining Visitors On-Site 588 

Providing resource services 589 

Creating message boards and chat sites 589 

The Don'ts of Web Site Promotion 589 

Unsolicited e-mail 589 

Redundant URL submissions 590 

Usenet newsgroup flooding 590 

Chat room or forum flooding 590 

Summary 590 

Chapter 38: Maintaining Your Site 591 

Analyzing Usage via Server Logs 59 1 

Monitoring Apache traffic 59 1 

Monitoring IIS Traffic 594 

Finding the right log analyzer 595 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents 



Checking for Broken Links 595 

The W3C Link Checker 595 

Checkers built into development tools 597 

Local tools 597 

Watching your logs 598 

Responding to Feedback 598 

Backing Up Your Data 599 

Summary 600 



Part VI: Principles of Professional Web Design 
and Development 



Chapter 39: The Web Development Process 603 

Challenges of Developing Large-Scale Web Sites 603 

Project Management Basics 604 

The Need for Information Architecture 605 

Overview of the Web Development Process 606 

Denning your goals 606 

Denning your audience 606 

Competitive and market analysis 606 

Requirements analysis 607 

Designing the site structure 607 

Specifying content 609 

Choosing a design theme 610 

Constructing the site 610 

Testing and evaluating the site 612 

Marketing the site 612 

Tracking site usage and performance 613 

Maintaining the site 614 

Summary 614 

Chapter 40: Developing and Structuring Content 617 

Principles of Audience Analysis 617 

Performing an Information Inventory 618 

Chunking Information 618 

How Users Read on the Web 619 

Developing Easily Scanned Text 619 

Developing Meta Content: Titles, Headings, and Taglines 620 

Titles 620 

Headings 620 

Taglines 620 

Characteristics of Excellent Web Writing 621 

Be concise 621 

Creating easily scanned web pages 621 

Maintaining credibility 622 

Maintaining objectivity 622 

Maintaining focus and limiting verbosity 622 

Writing in a top-down style 622 

Using summaries 623 

Writing for the Web 623 

Using bulleted lists 623 

Using a controlled vocabulary 624 

Jargon and marketese 624 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Contents XXI 



Basic Site Components 624 

Putting It All Together 625 

Summary 628 

Chapter 41 : Designing for Usability and Accessibility 629 

Usability Analysis Methods 629 

How People Use the Web 630 

Principles of Web Site Usability 630 

Usability Issues 63 1 

Advertising 63 1 

Animation, multimedia and applets 63 1 

Color and links 632 

Maintaining consistency 632 

Contents 632 

Drop-down menus 632 

Fonts and font size 632 

Using frames 633 

Including graphics 633 

Headings 633 

Horizontal scrolling 633 

JavaScript 634 

Legibility 635 

Searches 636 

Sitemaps 636 

URL length 636 

Taglines 636 

Windows 1252 character set 637 

The Need for Accessibility 63 7 

Accessibility Mandates 638 

Americans with Disabilities Act 638 

International 638 

Web Content Accessibility Initiative (W3C) 639 

Accommodating visual disabilities 639 

Providing access to the hearing-impaired 640 

Helping users with mobility disabilities 640 

Addressing those with cognitive and learning disabilities 640 

Tools you can use 640 

Using forms and PDF 643 

Checking accessibility using a validation service 643 

Summary 643 

Chapter 42: Designing for an International Audience 645 

Principles of Internationalization and Localization 645 

Introduction to Web Internationalization Issues 645 

Translating your Web site 646 

Understanding Unicode 647 

Basic Latin (U+0000 - U+007F) 650 

ISO-8859-1 650 

Latin- 1 Supplement (U+00C0 - U+00FF) 655 

Latin Extended-A (U+0100 - U+017F) 655 

Latin Extended-B and Latin Extended Additional 656 

Constructing Multilanguage Sites 656 

Summary 657 



P1:FMK 
WY022-FM 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



XXII 



Contents 



Chapter 43: Security 659 

Understanding the Risks 659 

Theft of confidential information 659 

Vandalism and defacement 659 

Denial of service 660 

Loss of data 660 

Loss of assets 660 

Loss of credibility and reputation 660 

Litigation 661 

Web Site Security Issues 661 

File permissions 661 

Unused but open ports 662 

CGI scripts 662 

Buffer overflows 663 

Compromised systems 663 

Overview of Web Security Methods 664 

Drafting a comprehensive security policy 664 

Checking online security warnings 664 

Excluding search engines 665 

Using secure servers 665 

Summary 666 

Chapter 44: Privacy 667 

Understanding Privacy 667 

Privacy Legislation and Regulations in the United States 667 

The Children's Online Privacy Protection Act 668 

Electronic Communications Privacy Act 669 

The Patriot Act of 2001 669 

Fair Credit Reporting Act 670 

Privacy Legislation and Regulations in the EU 670 

Voluntary Solutions 671 

Platform for Privacy Preferences project 671 

Certification and seal programs 674 

Model Privacy Policy Pages 675 

Summary 675 



Part VII: Appendixes 



Appendix A: HTML 4.01 Elements 679 

Appendix B: CSS Properties 743 

Index 773 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Introduction 



The World Wide Web has come a long way from its humble beginnings. Most 
Internet historians recognize Gopher as the precursor to the Web. Gopher was 
a revolutionary search tool that allowed the user to search hierarchical archives of 
textual documents. It enabled Internet users to easily search, retrieve, and share 
information. 

Today's World Wide Web is capable of delivering information via any number of 
medium — text, audio, video. The content can be dynamic and even interactive. 

However, the Web is not a panacea. The standards that make up the HTTP protocol 
are implemented in different ways by different browsers. What works on one 
platform may not work the same, if at all, on the next. Newly Web-enabled devices — 
PDAs, cell phones, appliances, and so on — are still searching for a suitable form of 
HTML to standardize on. 

This turmoil makes a book like this difficult to write. Although standards exist, they 
have been implemented in different ways and somewhat haphazardly. In addition, 
there are more technologies at work on the Web than can be easily counted. One 
book cannot hope to cover them all. 

This book attempts to cover a broad subset of available technologies and 
techniques, centering on the HTML 4.01 standard, along with a mix of newer, 
upcoming standards such as XML and XHTML. 



Who Should Read This Book? 



This book is geared toward a wide audience. Those readers who are just getting 
started with HTML and Web content will benefit the most as this book provides a 
decent learning foundation as well as ample reference material for later perusal. 
Experienced users will find the chapters covering new standards and technologies to 
be the most useful, and will also appreciate having a comprehensive reference for 
consultation. 

Although the Web is technical in nature, we have done our best to boil down the 
technology into simple and straightforward terms. Whether you are a computer 
scientist or a computer neophyte, you should be able to understand, adopt, and 
deploy the technologies discussed herein. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



XXlV Introduction 



Book Organization, Conventions, 
and Features 

The Wiley "Bible" series of books uses several different methods to present 
information to help you get the most out of it. The book is organized according to 
the following conventions. 

Organization 

This book is organized into logical parts. Each part contains related chapters that 
cover complementary subjects. 

Part I, Understanding (X)HTML, is your introduction to the HTML protocol. 

Part II, HTML and XHTML Authoring Fundamentals, continues coverage on the basics 
of the HTML protocol and familiarizes you with the basic HTML elements. 

Part III, Controlling Presentation with CSS, covers Cascading Style Sheets — covering 
how CSS works and introducing its various elements. 

Part IV, Advanced Web Authoring, delves into more advanced topics such as 
scripting, Dynamic HTML, and XML. 

Part V, Testing, Publishing, and Maintaining Your Site, covers more details about the 
tools and methodology for creating and publishing your content to the Web. 

Part VI, Principles of Professional Web Design and Development, covers more 
philosophical topics about developing structured, accessible content and how to 
protect your content online. 

Part VII, Appendixes, provides reference material on HTML tags, CSS conventions, 
and language codes. 



Conventions and features 

There are many different organizational and typographical features throughout this 
book designed to help you get the most from the information. 

Tips, Notes, and Cautions 

Whenever the authors want to bring something important to your attention, the 
information will appear in a Tip, Note, or Caution. These elements are formatted like 

this: 



Caution 



This information is important and is set off in a separate paragraph with a special 
icon. Cautions provide information about things to watch out for, whether these 
things are simply inconvenient or potentially hazardous to your data or systems. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



Introduction XXV 



Tip 



Note 



Tips generally are used to provide information that can make your work easier- 
special shortcuts or methods for doing something easier than the norm. 



Notes provide additional, ancillary information that is helpful, but somewhat 
outside the current discussion. 



Code 

It is often necessary to display code (HTML tags, JavaScript commands, script 
listings) within the text. This book uses two distinct conventions, depending on 
where the code appears. 

Code in Text 

A special font is used to indicate code within normal text. This font looks like this: 

<bodyonl_oad="JavaScript:displaygraphics();">. 

Code Listings 

Code listings appear in specially formatted listings, in a different font, 
similar to these lines. 



Feedback 



Wiley Publishing, Inc., and the authors of this book value your feedback. We 
welcome ways to improve the content presented here, such as being informed of 
errors and omissions. You can visit www . wi 1 ey . com for information on additional 
books and ways to provide feedback to the publisher. 



P1:FMK 

WY022-FM WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 15, 2004 23:23 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Understanding 
(X)HTML 



Chapter 1 

Introducing the 
Web and HTML 

Chapter 2 

What Goes Into 
a Web Page? 

Chapter 3 

Starting Your 
Web Page 



PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 




PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Introducing the 
Web and HTML 



This chapter addresses the questions most people have 
when they're getting started with HTML/XHTML, such as 
what is the difference between HTML and XHTML, and when 
do Cascading Style Sheets (CSS) come into play? If you're 
already familiar with the basic concepts discussed here, you 
can get started with practical matters in Chapter 2. Still, I 
encourage you to at least skim this chapter, making sure you 
understand the very important distinction between structure 
and presentation (see What Is CSS?) and how HTML, XML, and 
XHTML are related (see What Is XHTML?). 



What Is the World Wide Web? 

The World Wide Web — the Web, for short — is a network of 
computers able to exchange text, graphics, and multimedia 
information via the Internet. By sitting at a computer that is 
attached to the Web, using either a dialup phone line or a 
much faster broadband (Ethernet, cable, or DSL connection), 
you can visit Web-connected computers next door, at a nearby 
university, or halfway around the world. And you can take full 
advantage of the resources these computers make available, 
including text, graphics, videos, sounds, and animation. Think 
of the Web as the multimedia version of the Internet, and you'll 
be right on the mark. 



How Does the Web Work? 

The computers that make all these Web pages available are 
called Web servers. On any computer that's connected to the 
Web, you can run an application called a Web browser. 
Technically, a Web browser is called a Web client — that is, a 
program that's able to contact a Web server and request 
information. When the Web server receives the requested 










In This Chapter 

Introducing the World 
Wide Web 

How the Web Works 

Defining Hypertext 

Where HTML Fits in 

Defining CSS 

Defining XHTML 

Creating an HTML 
Document 

♦ ♦ ♦ ♦ 




PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Understanding (X)HTML 



information, it looks for this information within its file system, and sends out the 
requested information via the Internet. 

They all speak a common "language," called HyperText Transfer Protocol (HTTP). 
(HTTP isn't really a language like the ones people speak. It's a set of rules or 
procedures, called protocols, that enables computers to exchange information over 
the Web.) Regardless of where these computers reside — China, Norway, or Austin, 
Texas — they can communicate with each other through HTTP. 

The following illustrates how HTTP works (see Figure 1-1): 

♦ Most Web pages contain hyperlinks, which are specially formatted words or 
phrases that enable you to access another page on the Web. Although the 
hyperlink usually doesn't make the address of this page visible, it contains all 
the information needed for your computer to request a Web page from another 
computer. 

♦ When you click the hyperlink, your computer sends a message called an HTTP 
request. This message says, in effect, "Please send me the Web page that I want." 

4- The Web server receives the request, and looks within its stored files for the 
Web page you requested. When it finds the Web page, it sends it to your 
computer, and your Web browser displays it. If the page isn't found, you see an 
error message, which probably includes the HTTP code for this error: 404, "Not 
Found." 



HTTP 
request 



< Z 



Returns page or 
error message 



!^ 



^ 



=\ 



nun 

iiiiii 



m 



Client computer 
running browser 



^d 



Server 



Figure 1-1 : The client requests the page. Then the server evaluates 
the request and serves the page or an error message. 



What Is Hypertext? 



You probably noticed the word "hypertext" in the spelled-out version of HTTP, 
Hypertext Transfer Protocol. Originated by computing pioneer Theodore Nelson, the 
term "hypertext" doesn't mean "text that can't sit still," although some Web authors 
do use a much-despised HTML code that makes the text blink on-screen. Instead, the 
term is an analogy to a time-honored (but physically impossible) science fiction 
concept, the hyperspace jump, which enables a starship to go immediately from one 
star system to another. Hypertext is a type of text that contains hyperlinks (or just 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML 



links for short), which enable the reader to jump from one hypertext page to another. 
You may also hear the word hypermedia. A hypermedia system works just like 
hypertext, except that it includes graphics, sounds, videos, and animation as well as 
text. 

In contrast to ordinary text, hypertext gives readers the ability to choose their own 
path through the material that interests them. A book is designed to be read in 
sequence: Page 2 follows page 1, and so on. Sure, you can skip around, but books 
don't provide much help, beyond including an index. Computer-based hypertexts let 
readers jump around all they want. The computer part is important because it's hard 
to build a hypertext system out of physical media, such as index cards or pieces of 
paper. 

The Web is a giant computer-based hypermedia system, and you've probably already 
done lots of jumping around from one page to another on the Web — it's called 
surfing. If one Web page doesn't seem all that interesting once you visit, you can click 
another link that seems more related to your needs (and so on). The Web makes 
surfing so easy that you'll need to give some thought to keeping people on your 
sites — keeping them engaged and interested — so they won't surf away! 



Where Does HTML Fit In? 



Hypertext Markup Language (HTML) enables you to mark up text so that it can 
function as hypertext on the Web. The term markup comes from printing; editors 
mark up manuscript pages with funny-looking symbols that tell the printer how to 
print the page. HTML consists of its own set of funny-looking symbols that tell Web 
browsers how to display the page. These symbols, called elements, include the ones 
needed to create hyperlinks. 



The invention of HTML 

HTML and HTTP were both invented by Tim Berners-Lee, who was then working as a 
computer and networking specialist at a Swiss research institute. He wanted to give 
the Institute's researchers a simple markup language, which would enable them to 
share their research papers via the Internet. Berners-Lee based HTML on Standard 
Generalized Markup Language (SGML), an international standard for marking up text 
for presentation on a variety of physical devices. The basic idea of SGML is that the 
document's structure should be separated from its presentation: 

♦ Structure refers to the various components or parts of a document that authors 
create, such as titles, paragraphs, headings, and lists. For example, you're 
reading an item in an unordered list, as it is termed in SGML (most people use 
the more familiar bulleted list). In SGML, you mark up this item as a bulleted 
list, but you don't say anything about how it's supposed to look. That's left up 
to whatever device displays or prints the marked-up file. 

♦ Presentation refers to the way these various components are actually displayed 
by a given media device, such as a computer or a printer. For example, this 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Part I ♦ Understanding (X)HTML 



book displays this bulleted list item with an indentation and other special 
formatting. 

What's so great about separating structure from presentation? There are several 
very important advantages: 

♦ Authors usually aren't very good designers. It's wise, especially in large 
organizations, to let writers compose their documents, and let designers worry 
about how the documents are supposed to look. That's particularly true when 
an organization has a corporate look or style, such as Apple Computer's 
standard typeface, which you'll see in all of its documents. The designers make 
sure that every document produced within the organization conforms to that 
style. So SGML doesn't contain any features that control presentation. 

♦ If markup consists of structure alone, the document's appearance can be changed 
quickly. All that's necessary is to change the presentation settings on whatever 
device is displaying the document. 

♦ Documents containing only structural markup are much easier and cheaper to 
maintain. When presentation markup is included along with structural markup, 
the document becomes an unmanageable mess, and maintenance costs 
skyrocket. 

♦ If a document contains only structural markup, it is more accessible to people with 
limited vision or other physical limitations. For example, a document marked up 
structurally might be presented by a Braille printer for those with limited 
vision, or by a text reader for those with limited hearing. 

Sounds great, right? Still, from the beginning, HTML didn't make the structure versus 
presentation distinction as clearly as SGML purists would have liked. And as HTML 
developed and the Internet became a commercial network, Web authors demanded 
more tools to make their documents look attractive on-screen. The companies that 
make Web browsers responded by introducing new, nonstandardized HTML 
elements that contained presentation information. By 1996, many Web experts were 
worried that HTML standards were spiraling out of control. The newly founded World 
Wide Consortium, hoping to keep at least some kind of standard in place, tried to 
standardize existing practices, including the use of presentation and structure. The 
result was the W3C's HTML 3.2 standard, which is still widely used. But organizations 
found that HTML 3.2 exposed them to excessive maintenance costs. The SGML 
purists were right: Structure and presentation should have been kept separate. 



A short history of HTML 



To date, HTML has gone through four major standards, including the latest 4.01. In 
addition to the HTML standards, Cascading Style Sheets and XML have also provided 
valuable contributions to Web standards. 

The following sections provide a brief overview of the various versions and 
technologies. 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML 



HTML 1.0 

HTML 1.0 was never formally specified by the W3C because the W3C came along too 
late. HTML 1.0 was the original specification Mosaic 1.0 used, and it supported few 
elements. What you couldn't do on a page is more interesting than what you could 
do. You couldn't set the background color or background image of the page. There 
were no tables or frames. You couldn't dictate the font. All inline images had to be 
GIFs; JPEGs were used for out-of-line images. And there were no forms. 

Every page looked pretty much the same: gray background and Times Roman font. 
Links were indicated in blue until you'd visited them, and then they were red. 
Because scanners and image-manipulation software weren't as available then, the 
image limitation wasn't a huge problem. HTML 1.0 was only implemented in Mosaic 
and Lynx (a text-only browser that runs under UNIX). 

HTML 2.0 

Huge strides forward were made between HTML 1.0 and HTML 2.0. An HTML 1.1 
actually did exist, created by Netscape to support what its first browser could do. 
Because only Netscape and Mosaic were available at the time (both written under 
the leadership of Marc Andreesen), browser makers were in the habit of adding their 
own new features and creating names for HTML elements to use those features. 

Between HTML 1.0 and HTML 2.0, the W3C also came into being, under the 
leadership of Tim Berners-Lee, founder of the Web. HTML 2.0 was a huge 
improvement over HTML 1.0. Background colors and images could be set. Forms 
became available with a limited set of fields, but nevertheless, for the first time, 
visitors to a Web page could submit information. Tables also became possible. 

HTML 3.2 

Why no 3.0? The W3C couldn't get a specification out in time for agreement by the 
members. HTML 3.2 was vastly richer than HTML 2.0. It included support for style 
sheets (CSS level 1). Even though CSS was supported in the 3.2 specification, the 
browser manufacturers didn't support CSS well enough for a designer to make much 
use of it. HTML 3.2 expanded the number of attributes that enabled designers to 
customize the look of a page (exactly the opposite of HTML 4). HTML 3.2 didn't 
include support for frames, but the browser makers implemented them anyway. 

Note A page with two frames is actually processed like three separate pages within 

your browser. The outer page is the frameset. The frameset indicates to the 
browser, which pages go where in the browser window. Implementing frames 
can be tricky, but frames can also be an effective way to implement a Web site. 
A common use for frames is navigation in the left pane and content in the right. 

HTML 4.0 

What does HTML 4.0 add? Not so much new elements — although those do exist — as 
a rethinking of the direction HTML is taking. Up until now, HTML has encouraged 
interjecting presentation information into the page. HTML 4.0 now clearly 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



8 Part I ♦ Understanding (X)HTML 



deprecates any uses of HTML that relate to forcing a browser to format an element a 
certain way. All formatting has been moved into the style sheets. With formatting 
information strewn throughout the pages, HTML 3.2 had reached a point where 
maintenance was expensive and difficult. This movement of presentation out of the 
document, once and for all, should facilitate the continued rapid growth of the Web. 

Tip Use the W3C's MarkUp Validation Service, available at http : //val i dator 

. w3 . org/, to check your HTML against most of the versions mentioned in this 
' chapter. 

XML 1.0 

Extensible Markup Language (XML) was originally designed to meet the needs of 
large-scale electronic publishing. As such, it was designed to help separate structure 
from presentation and provide enough power and flexibility to be applicable in a 
variety of publishing applications. In fact, many modern word processing programs 
contain XML components or even export their documents in XML-compliant formats. 

CSS 1.0 and 2.0 

Cascading Style Sheets (CSS) were designed to help move formatting out of the 
HTML specification. Much like styles in a word processing program, CSS provides a 
mechanism to easily specify and change formatting without changing the underlying 
code. The "cascade" in the name comes from the fact that the specification allows 
for multiple style sheets to interact, allowing individual Web documents to be 
formatted slightly different from their kin (following department document 
guidelines but still adhering to the company standards, for example). The second 
version of CSS (2.0) builds on the capabilities of the first version, adding more 
attributes and properties for a Web designer to draw upon. 

HTML 4.01 

HTML 4.01 is a minor revision of the HTML 4.0 standard. In addition to fixing errors 
identified since the inception of 4.0, HTML 4.01 also provides the basis for meanings 
of XHTML elements and attributes, reducing the size of the XHTML 1.0 specification. 

XHTML 1.0 

Extensible HyperText Markup Language (XHTML) is the first specification for the 
HTML and XML cross-breed. XHTML was created to be the next generation of 
markup languages, infusing the standard of HTML with the extensibility of XML. It 
was designed to be used in XML-compliant environments, yet compatible with 
standard HTML 4.01 user agents. 



So who makes the rules? 

Every organization has its own rule-making body. In the case of the Web, the 
rule-making body is the World Wide Web Consortium (W3C). The W3C is composed 
of representatives from a number of high-tech companies who want to have a say in 
the standards. The W3C tries to balance the interests of the academy, the companies 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML 



producing the Web browsers (notably Netscape and Microsoft), and the technology. 
The W3C pulls together committees with representatives from interested members 
and puts the specifications in writing for HTTP and HTML, as well as a host of 
additional Web standards, including CSS. If the W3C weren't maintaining all these 
standards, the Web wouldn't be as easy to use; in fact, it might not have become 
anywhere near as popular as it is. You can visit their Web site at http : / /www . w3c 
.org. 

Buzz and scrambling 

How does the W3C decide when a new technology must be standardized or a new 
version of an existing technology must be developed? Newsgroups and mailing lists 
exist where leading figures in the relevant field talk about the shortcomings of an 
existing version or the idea of a new technology (that's the buzz). If a ground swell of 
support seems to exist for a new technology or a new version, the W3C begins the 
process of specifying it. 

Something else, however, carries more weight and more urgency than discussion by 
agitators and activists. This is ongoing development by software developers (that's 
the scrambling). In reality, the W3C is mostly involved in trying to standardize the 
proprietary extensions developed by software developers, such as Netscape and 
Microsoft. If the W3C didn't do this, within two versions of their browsers, HTML 
might not run the same (or at all) on both systems. The W3C reins them in to some 
degree. Neither wants to produce a browser that lacks support for recommended 
HTML elements, so even if Netscape introduced a new element, Microsoft will 
incorporate that element in the subsequent version of their own browser — after an 
official recommendation by the W3C (and vice versa). 

Committees and working drafts 

When a new technology or a new version of an existing technology is required, the 
W3C convenes a committee of interested parties to write the specification. The 
committee publishes its work on an ongoing basis as a working draft. The point of 
publishing these working drafts is this: Software developers who want to implement 
the new technology or the new features of the new version can get a jump on things 
and build their product to incorporate the new features. When the specification is 
finalized and developers are ready to use it, products that implement it are on the 
market. 

There is also the issue of books. You want books on new technologies to be in the 
bookstores the day the recommendation is finalized. For this to happen, authors 
must write the books using the working drafts — a moving target — as the reference 
materials. Working drafts have changed during the writing of this book. Sometimes 
this works and sometimes it doesn't. If the specification changes radically from the 
working draft to the final version, the book will be inaccurate. 

Voting process 

Democracy: You just can't get away from it. When a working draft reaches a point 
where the committee is pleased and believes it is complete, the working draft is 



PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Part I ♦ Understanding (X)HTML 



released to the public as a proposed recommendation. Members of the W3C have up 
to six weeks to vote on it — votes can take the form of any one of three choices: yes, 
yes if certain changes are made, or no. At the conclusion of the voting process, the 
W3C can recommend the specification officially, make the requested changes and 
recommend the specification with the changes, or discard the proposal. 



What Is CSS? 



In 1997, the World Wide Web Consortium released the first HTML 4 recommendation, 
the first to embody a serious effort to separate structure from presentation. The W3C 
envisioned a transitional period, in which Web authors would continue to use some 
presentation features in their pages, but the end point was clear: Any Web page that 
wanted to conform strictly to HTML would have to omit presentation-related coding. 

To see for yourself how difficult maintaining HTML 3.2 code can be, consider the 
following HTML: 



<li> 

COLO 

Touc 

<F0N 

COLO 

the 

who 

mana 

site 

site 

then 

cri t 

read 

the 

<li> 

COLO 

1 i st 

<F0N 

COLO 

to y 

resi 

secu 

thin 



FONT 

="#00 

</i 

SIZE 
="#00 
ower 
i s i t 
ement 
today 

Your 
you c 
ri a : 

etc . 
end M 
FONT 
="#00 
</ 

SIZE 
="#00 
ur 1 i 
i ng o 
ity o 
s.</P 



SIZE= 
00FF" 
do?</ 

-1" 



of 

yo 

s 

a 

v 
an 
th 

T 
ai 
SI 
00 
/PX. 
=■■-!' 



+1" FACE="c 
XPXA name= 
BX/PX/F0NT 

FACE="comi c 
XPXiXtay 
e World Wide 
web site. Us 
ice you can 
customize it 
tors can sig 
nd mai 1 to y 
nterest they 
ee an exampl 
ption.XPX/ 
"+1" FACE="c 
XPXA name= 
FONT) 

FACE="comi c 
XPXnly you 

available e 

server. You 
r list needn 
NT> 



omic sans ms" FAMI LY="sans -seri f ' 
o"X/aXB>What does <i>Stay In 



san 

In T 

Web 
ing 
set 

to 
n i n 
our 

i nd 
e of 
FONT 
omi c 

sec 



s ms" FAMI LY="sans -seri f" 
ouch</i> allows you to harness 

to communicate with people 
<i>Stay In Touch</i> list 
up a sign-in page on your web 
match the rest of your web 
to your site when they visit, 
visitors based on a number of 
icate, the publications they 

this, go to the Demo and view 
> 

sans ms" FAMI LY="sans -seri f" 
urity"X/aXB>How secure is my 



sans ms" FAMILY="Sans Serif" 
have access to your list. Access 
xclusively from secure pages 
have enough to worry about. The 
t be one of those 



Figure 1-2 shows what this HTML code looks like in a full page on a PC, while 
Figure 1-3 shows what that same page looks like on a Mac (notice that the font is 
slightly different). 



The maintenance nightmare 



From looking at the HTML and then seeing the HTML interpreted by the browser, 
you can pretty much tell what part of the text is instructions to the browser and 



PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML 



EBsnmwmm 



Fie Edil Ve^v Gd Ccmrw-ricatcr Help 



^l _tf a A *■ 13 s* > It 

Bock -or^c RsloDd Horn; ScDich Guide Prhl 5ccurr.> Stos 



^^f Dookrrerki ^ Location: |htlpv/*Y/w\.ovefheweb.c 



Over 
lhe\Web/ 




Vakihg th« W« b w ■> rk f o r you. 



D 


LSt 


srnen tervice i hvTJ 


i-mo 




Pure, hose 


Pr 


T II 




^rl-nini^rKh Vn in 1 irt 


CiL 


jsouritv 


■ 


f"jnr-rin rrrt? PhilrRnpky 








ft 


telecses 

|coldfiisibn| 



DDCumcrt: Dorc 



If. What, if anything, dues Over fj« Kjej attach in the hattam at 



13. Hw da I tct billed? 

IV. When is if tilling date? 

20. What rf I rani tc cIbjc if account? 



iL 



1. What d*es .Sftip In Tenth do? 

j'c/j' Z0 Tl-lc-vv ul lu>vs yuu lu hurries I lit pjv&r uf I hi Wu -, ld Wide V/eb 
■fr i^nmni in i "fi"rp urith pcr-plc .jd-n vmt ynir wph ^it?. UirQ .Trvrj.' fa 
Tvuth I i 3"t nanaaeirent service you ccn set up asiar in Daae on your .veb 
sile I jday urid juslurr \<x, i I lu rruldi lie rvs uf yuj M wtb sile. Yuur 
vis tors cm sign irto ycur site jM-izn tiey visit, - hcn ycu ten send nail 
tc yoLr visitors based oi c number of criteria the interest they 
ird cate. - he publ cat ere they reid. etc. To see an exanpls cf - hs. go 
tc the ^cno end view the berd Ska 1 optior. 

Z. Haw secure Is my list? 

Oi y vol have access to your list, /ccess to your list is cvs. lable 
exclusively "frorr secure pages residing on nut 1 server. Voj hove eiough 
to no pry about. I he sc-cu r i t/ of your I st necdi't se oie of those 
tl-ing;. 



■JUS 



3 



"3 



J 



il m :'«. SP 



^ I 



Figure 1-2: How a PC browser displays the HTML code. 



*| File Edit View Go Doakmnrks Options Director Window Help 

■ -JF - ■ - 



I Netscape: Over Trie Web 



Hack 


rcrrf*rd 


,§, 




Reload 


j§ 


*• 

Of*. 


Ti-int 


J? 

Mid 


Stop 



!'■"■■ "■" 



Live Home figt 1 1 N?t Search 1 1 flpp e Cofput?r | | Apple Support | Apjfe Software | 




Over 
'theNWeb/ 



Me kin g lh e We b w ■;■ rk for ysu. 



cemm o from? 
. What, if cny-hng, cbes 'Z*>e? tfs '&si> attacr ~o - re 

boTrom o z ruif nail messages? 
. Ha'tf da I c et billed? 



.ILL* 



Cu-I 


ri¥i-5wrv 


^ & RS 




^miL 




Fui dim* 


PlV^V 




/.d 


niniz-lerYj 


iLi-.l 


Jlgr In 


JecurJiy 


Co 


porate PI 


llcssphy 





5tnyti) Ttwah ailoiAsyoL lohorhess ■kepoiwr of ths Wcrd 
TV id e Wjb r c corrmui co.te wi1 h peop k y/i o m i ; it yjL r i^veb site 
Jshc S'.cySa Ttumfr list nonoce-neht service yoj con ser up o. 
slqh-npaqe en your web s 11 e tod o.y ond custontzc It to match 1li 



lu yuui 



:«J U-l 



Press Re e^ses 



.xcinpl< of thij, 3 c lotlie'OtnucHjd 



CCLDFUSICH 



O-ilyyoi. dout 3 



Figure 1-3: The previous text displayed in a browser on a Mac. 



PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Understanding (X)HTML 



what part is the content. But would you feel comfortable making changes to the 
content — say, adding another bulleted set of questions and answers? Probably not. 
With all those codes embedded within the text, you might mess something up. And 
you probably wouldn't want someone else who didn't know what all those codes 
meant doing it either. 

The worst maintenance nightmares occur when you want to change the look of your 
pages throughout your Web site. Because the presentation code has to be included 
in every page, you have to change every page to change the look of your site. 

Consider the site map shown in Figure 1-4. Every screen should have the same 
formatting: same font, same heading sizes, same alignment, same text color, and 
same background color. With HTML 3.2, you could do this only by inserting all the 
needed presentation code on every single page. 



File Edt Co View Hep 






' ' 


5© (© y @ 

Prfuiew He™ Page Go to .131 





CFUG 



fe ®. «, 



Calendar Join Meetin.. 



JL 



, Frame... Present. 



■^ / 




Heady 

Figure 1-4: Map of a Web site. 



HTML 4.01 enables you to return to the ideal of separating structure and 
presentation. What does this mean to you and your ability to maintain a site? It's 
simple. HTML that contains nothing but structural code is vastly simpler and 
cheaper to maintain. 

Consider the following code. It produces the same results as the previous example in 
the browser. Notice there is no formatting. All the HTML you see is related to the 
structure. 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML ] 3 



< 1 i > W h a t does <i>Stay In Touch</i> do?</li> 
<p><i>Stay In Touch</i> allows you to harness the power of 
the World Wide Web to communicate with people who visit your 
web site. Using <i>Stay In Touch</i> list management service, 
you can set up a sign-in page on your web site today and 
customize it to match the rest of your web site. Your 
visitors can sign into your site when they visit. Then you 
can send mail to your visitors based on a number of criteria: 
the interest they indicate, the publications they read, etc. 
To see an example of this, go to the Demo and view the Send 
Mail option.</p> 
<li>How secure is my 1 i s t ? < / 1 i > 

<p>0nly you have access to your list. Access to your list is 
available exclusively from secure pages residing on our 
server. You have enough to worry about. The security of your 
list needn't be one of those things.</p> 

Note The use of the italic tags (<i >) in the preceding code is arguably "formatting" 

and is used to simplify the example while conforming to the visual style of the 
text "Stay In Touch." When using HTML 4.01 and CSS it might be better to use 
span tags (<span>) to refer to a CSS class instead of directly specifying the italic 
text attribute. See Chapter 16 for more information on styles and span tags. 

How comfortable would you be updating the previous HTML? How about if you 
needed to add another set of questions and answers? Already, you can see that using 
HTML 4.01 makes a world of difference. 

There's only one problem. The simpler, HTML 4.01-compliant code looks just terrible 
on-screen; with no presentation information in the code, the browser falls back on its 
default presentation settings. 



Enter CSS 

By themselves, strictly conformant HTML 4 documents are ugly. Web authors would 
never have accepted HTML 4 if the W3C had not also developed Cascading Style 
Sheets (CSS). In brief, CSS enables Web authors to specify presentation information 
without violating the structure versus presentation distinction. The information the 
browser must know to format the previous text is stored separately, in a style sheet. 
The style sheet lists the presentation styles that the browser should use to display 
the various components of the document, such as headings, lists, and paragraphs. 
The style sheet is kept separate from the marked-up text. It can be stored in a special 
section of the HTML document itself, away from the document's text, or in a separate 
file entirely. 

The idea and the name come from the publishing industry, where style sheets are 
still used today. And they're cutting costs wherever Web documents are created and 
maintained. 

Think back to the problem of updating a Web site's look, discussed earlier. Without 
CSS, you'd have to make changes to the presentation code in each and every page. 



PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Part I ♦ Understanding (X)HTML 



Thanks to CSS, all you have to do is make changes to the single, underlying style 
sheet that every page uses, and the entire site's appearance changes. 

What does "cascading" mean? 

In Cascading Style Sheets, the term "cascading" refers to what computer people call 
the order of precedence — that is, which style information comes first in the style 
pecking order. Here's the order: 

♦ Element-specific style information comes first. This is style information that's 
embedded within the HTML. But wait — doesn't this violate the structure 
versus presentation rule? Yes, but sometimes it's necessary. If element-specific 
information is given, it takes precedence over page-specific and global styles. 

♦ Page-specific style information is kept in a special section of the document, 
called the head, that's separate from the text. It defines the way a particular 
page looks. If page-specific information is given, it takes precedence over 
global styles. 

♦ Global styles are specified in a separate style sheet file. They come into play 
unless conflicting element- or page-specific styles are given. 

See Figure 1-5 for a summary of these points. 



Global styles defined in their 
own document: GLOBALCSS 



HTML page 
PAGE.HTML 



-specific (also known 
as local) styles defined 
within an HTML document 
(in the HEAD), using the 
STYLE element. 



Element-specific styles are 
defined within the element 
definition using the STYLE 
attribute. 



Figure 1-5: The cascading model of style definitions. 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML 



HTML 4.01 almost eliminates the need to have an HTML expert perform site 
maintenance. This means HTML 4.01 helps reduce the cost of maintaining your Web 
site. When was the last time you heard anything about reducing costs being 
associated with the Web? 



What Is XHTML? 



Combined with CSS, HTML 4.0 was a major advance, so one might expect even better 
versions of HTML in the future, right? Not according to the World Wide Web 
Consortium. Apart from a minor update (HTML 4.01) in 1999, HTML 4.0 is the last 
version of HTML. That's because it has been replaced by XHTML, which is the 
version of HTML you're going to learn in this book. 

Actually, there's very little difference between HTML and XHTML. It's a matter of 
making a few changes to your HTML 4.0 code to make sure it's XHTML-conformant. 
But there's a much deeper reason for this change. To understand why HTML has 
become XHTML, you must learn a little about XML, another World Wide Consortium 
standard. 

As you've learned, HTML is based on SGML, an international standard for markup 
languages. Actually, SGML isn't a markup language in itself. It's a language that's 
useful for creating markup languages. You can use it to make up codes for just about 
anything you want. For example, an accounting firm could use SGML to mark up the 
structure of accounting documents; one code could be used to mark daily totals, 
while a different code could be used to mark monthly totals. To keep a record of all 
these newly created codes, as well as to specify them for presentation devices, a 
special file, called a document type definition (DTD), is used. HTML 4.01 is defined in 
a document type definition, written in SGML. 

SGML isn't equally loved by all. To many, SGML is outmoded, overly complex, and 
too difficult to learn. So the World Wide Consortium decided to create a new version 
of SGML that would be simpler and easier to learn. The result is the Extensible 
Markup Language (XML). Like SGML, XML enables people to define new markup 
languages that are exactly suited to their purposes. 

Now that you know a little about what XML is, you're ready to understand what 
XHTML is. Just as HTML is a markup language defined in SGML, XHTML is a markup 
language defined in XML. 



Creating an HTML Document 



Creating an HTML document is relatively easy. One of the nice properties of HTML is 
it is just text. The content is text and the tags are text. As a result, you can write your 
HTML in any text editor. If you are running any variety of Windows, you can use 
Notepad, which comes installed with Windows. If you have a Mac on your desk, you 
can use SimpleText. If you work in UNIX, you can use emacs, vi, jove, pico, or 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Understanding (X)HTML 



whatever you normally use to edit text. Essentially, any text editor or editor capable 
of producing text-only documents can be used to create HTML documents. 



Writing HTML 



What else do you need to know to write your HTML? Presumably, by now, you know 
the following: 

♦ What your purpose is (at least generally) 

♦ You need to write your content from your focused message 

♦ You mark up your content with HTML tags 

♦ You can write your page with a text editor that is already installed on your 
computer 

Obviously, you need to know the elements. But before discussing those, here are a 
few guidelines about how you should and shouldn't use HTML. 



Name your files with a Web-friendly extension 

When saving an HTML file you should always give it a . html or . htm extension. 
(The former, . html , is generally preferred.) This correctly identifies the file as 
having HTML content so that Web browsers and servers correctly handle it. 

Other Web files have their own extensions — for example, most PHP files use . php, 
graphic files use . j pg, . gi f , or . png, and so on. This book suggests appropriate 
extension(s) as each technology is discussed. 



Format your text 



If you are already writing HTML pages, you may need to break your bad habits. You 
probably already think in terms of getting the browser to make your page look the 
right way. And you use HTML to make it do this. You may even use goofy 
conventions such as 1-pixel-wide clear image files (usually GIFs) and stretch them to 
indent your paragraphs. 

With HTML 4, you needn't out-maneuver the browser. Browsers that support the 
HTML 4 standards display your pages as you define them — no more of that arrogant 
printer stuff! And fortunately, with HTML 4, you can define the way you want your 
pages to look outside of the content, so your HTML won't be all cluttered with tags. 



Structure your document 



So, if you are not supposed to use HTML to format your pages, how should you use 
HTML? 



PI: JYS 

WY022-01 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Chapter 1 ♦ Introducing the Web and HTML 



HTML defines your document's structure. Then, outside the main body of the 
document (or even in a separate file, if you prefer), you define the appearance of 
each element of the structure (just like the publisher and the printer in the previous 
example). 

With few exceptions, you want all your paragraphs to be formatted the same — 
uniform margins, indents, fonts, spacing between lines, and color. 

So, within the main body of your document, you type your text for each paragraph 
and mark up your document to indicate where each paragraph begins and ends. 
Then, in a separate location and only once, you define how you want all your 
paragraphs to look. Existing ways to override this universal definition are discussed 
later. 

The most important concept to remember — and this is a big change for you if you've 
already been writing HTML 3.2 or earlier versions — is that the HTML only defines the 
structure of your document. The formatting of your document is handled separately. 

What is so great about this? First, your text doesn't get all cluttered up with tags. 
And second, you can define the look for your entire site in one place. You simply 
have every page in the site (even if some pages in your site are being written by 
people you have never met) point to the style sheet (the place where you put all 
those style definitions). 



Don't I Need a Web Server? 



- 



Later chapters will show you how to upload your documents to a dedicated and 
public Web server where others can see them. In the meantime, you can simply use 
your computer's hard drive and a local browser to dabble privately with HTML. 



Note Server-side technologies such as PHP require an actual Web server. 



Simply put the document on your hard drive and direct your browser at the file. For 
example, in Windows you can double-click an HTML file in Windows Explorer (or any 
other file manager) to open it in the default browser (normally Internet Explorer). 
Most browsers also have an Open File option under their main File menu. 

Create additional files, directories, and subdirectories on your local hard drive as 
needed to hold additional pages or levels of a site. 

Tip Apache, the Web's most popular HTTP server, is available for several architec- 

v tures and best of all, it's free to use. If you need a local Web server for testing 

J purposes, visit the Apache Website (h tip ://httpd. apache, org/) for more 

information or to download a copy for your machine. For more information on 

Apache, see Wiley's Apache Server 2 Bible, 2nd Edition, by Mohammed J. Kabir. 



PI: JYS 
WY022-01 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 11:19 



Part I ♦ Understanding (X)HTML 



Summary 



This chapter covered the basics of HTML and the Web. Before actually creating Web 
documents, it is important to understand the evolution of the technologies behind 
the Web, and the direction they will take in the future. The next few chapters discuss 
the basic elements of HTML documents and get you on your way to creating your 
own Web content. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



What Goes Into 
a Web Page? 



HTML has come a long way from its humble beginnings. 
However, despite the fact that you can use HTML (and 
its derivatives) for much more than serving up static text 
documents, the basic organization and structure of the HTML 
document remains the same. 

Before we dive into the specifics of various elements of HTML, 
it is important to summarize what each element is, what it is 
used for, and how it affects other elements in the document. 
This chapter provides a high-level overview of a standard 
HTML document and its elements. Subsequent chapters will 
cover each element and technology in detail. 



Specifying Document Type 

One attribute of HTML documents that is frequently 
overlooked is the Document Type Definition (DTD). This 
definition precedes any document tags and exists to inform 
client browsers of the format of the following content — what 
tags to expect, methods to support, and so forth. 

The < ! DOCTY PE> tag is used to specify an existing DTD. The 
DTD contains all the elements, definitions, events, and so on 
associated with the document type. A DOCTY PE tag resembles 
the following: 



<!D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/htnil4/strict.dtd"> 

This tag specifies the following information: 

♦ The document's top tag level is HTML (html ). 

4- The document adheres to the formal public identifier (FPI) 
"W3C HTML 4.01 Strict English" standards (PUBLIC " - / / 
W3C//DTD HTML 4.01//EN"). 







♦ ♦ ♦ ♦ 

In This Chapter 

Specifying the Document 
Type 

HTML, Head, and Body 
Tags 

Styles 

Markup for Paragraphs 

Markup for Characters 

Special Characters 

Organizational Elements 

Linking to Other Pages 

Images 

Comments 

Scripts 

Putting it All Together 

♦ ♦ ♦ ♦ 




19 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



20 Part ' ♦ Understanding (X)HTML 



♦ The full DTD can be found at the URL http : / /www . w3 . org/TR/ 
xhtml 1/ DTD /xhtml 1- strict. dtd. 



The Overall Structure: HTML, 
Head, and Body 



All HTML documents have three, document-level tags in common. These tags, 
<html >, <head>, and <body>, delimit certain sections of the HTML document. 



The<html>tag 



The < hit ml > tag surrounds the entire HTML document. This tag tells the client 
browser where the document begins and ends. 



Chtml> 

. . . document contents 
;/html> 



Additional language options were declared within the < hit ml > tag in previous 
versions of HTML. However, those options (notably 1 ang and di r) have been 
deprecated in HTML version 4.0. The language and directional information is 
routinely contained in the document type declaration (< ! D0CTY P E>). 



The <head> tag 



The < h e a d > tag delimits the heading of the HTML document. The heading section of 
the document contains certain heading information for the document. The 
document's title, meta information, and, in most cases, document scripts are all 
contained in the < h e a d > section. A typical < h e a d > section could resemble the 
following: 

<head> 

< 1 ink rel ="styl esheet" type="text/css" href="/styl es . css"> 

<title>Title of the Document</ti tl e> 

<meta name="descri pti on" content="Sampl e Page") 

<meta name="keywords" content="sampl e , heading, page") 

<script 1 a nguage=" Java Script") 

function NewWindow(url){ 

fin=window.open(url ,"", 

"width=800,height=600,scrollbars=yes,resizabl e=yes" ) ; 

) 
</script> 
</head> 




level tags are covered in detail in Chapter 3. JavaScript scripting 
is covered in more detail in Chapters 15 and 28. 



Cross- \ Most < head 
Reference 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



Most of the content within the <head> section will not be visible on the rendered 
page in the client's browser. The <title> element determines what the browser 
displays as the page title — on Windows machines, the document title appears in the 
browser's title bar, as shown in Figure 2-1. 



Document title 

I 



|^J The Dtcla rati on of Independence - Microsoft Internet Explorer 
File Edit View Favorites Tools Help 



i! 



Arlrlre^ ^\ http : //loc^host/sampJe . html 



~BE< 



IN CONGRESS, July 4, 1775. 

The unaiiiirLOiis Declaration of the thirteen united States of America, 

When m the Course ot'human events, it becomes necessary lor cne people to cissolve the political bands which have 
coanected then: with another, and to assume among the powers of the earth, the separate £nd equal station to which the Lsws 
of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the 
causes which impel them to the separation. 

"We hold these truths to be self-evident that all men are created equal, that they are endowed by their Creator with certain 
unalienable lights, ttat arnon^ these are Life, Lberty and the pursuit of Happiness --That to secure these ngbts. Governments 
are Lnstitu:ed among Hen, deriving their just powers from the consent of tie governed, —That whenever any Form of 
Government become: destructive of these ends, it is the Eight of the People to alter or to abolish it, and to institute new 
Government, laying its foundation on such principles and organizing Lts oo n .ve/s o such form, as to them shall ;ecm most likely 
L'j effeuL tier: SiifeLy and Happiness. Pzudciuc, indeed, vvil dhLaLe llial GuvenoieuLa lung established should not be uhanged 
for light and transient causes; anc accordingly al experience hath shewn, that mankind are more disposed to suffer, while evils 
are sufferable, than to right themselves by abohshing the forms to which they are accustomed. But when a long train of abuses 
and usurpations, pursuing invariably the same Cbject evinces a design to reduce them ur.der absolute .Despotism, i: is their 
ngh:, it is their duty, to throw off such Government, and to provide new Guards for their future security.— Such has be en the 
patient sufferance of these Colonies, and such is now the necessity whi;h constrains them to alter their former Systems of 
Government The history of the pre sen: Kin£ of Ore a: Britain is a history of repeated iniunes and usurpations, al having m 
cirect object the establishment of ar. absolute Tyranny over these States. To prove this, '.et Facts be submitted to £ candid 
world. 



_, 



@Doie 



*j Local intranet 



Figure 2-1: In Windows, the document's <ti tl e> appears in the browser's title bar. 

The main, visual content of the HTML document is contained within <body> tags. 

Note that with HTML version 4.0, most attributes of the <body > tag have been 
deprecated in favor of specifying the attributes as styles. In previous versions of 
HTML, you could specify a bevy of options, including the document background, 
text, and link colors. The onload and onunl oad attributes of the <body> tag, as 
well as global attributes such as sty 1 e, are still valid. However, you should specify 
the other attributes in styles instead of within the <body> tag, such as in the 
following example: 



Chtml > 

;head> 

<t i tl e>Document Ti tl e</t i tl e> 
<style type="text/css"> 
body 1 background: black; color: 



white) 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



22 Part I ♦ Understanding (X)HTML 



a:link { color: red I 
a:visited { color: blue 1 
a:active ( color: yellow 
</style> 

;/head> 

(body) 

. . . document body. . . 

;/body> 

;/html> 




Cross- 
Reference 



Styles are covered in detail in Chapters 16 and 24. 



Styles 



Note 



Styles are a relatively new element for HTML, but they have revolutionized how 
HTML documents are coded and rendered. Styles are the main basis behind the 
"extensible" in XHTML — they allow Web authors to create new styles to present their 
content in a variety of custom, but consistent formats. 

At their root, styles are simply an aggregation of display attributes, combined to 
achieve a particular result. Those familiar with styles in word processing will have 
little trouble understanding HTML styles. 

Styles are typically presented in the context of cascading, as in the Cascading 
Style Sheet (CSS) standard. The CSS standard defines a method where several 
styles sheets (lists of style definitions) can be applied to the same document- 
repeated style definitions supercede previously defined styles, hence the 
cascade. You'll find more information on styles, style sheets, and CSS in 
Chapter 16. 

For example, suppose you needed to highlight particular text in a document that 
needed to be deleted. The text needs to be displayed in red and as strikethrough. 
You could surround each section of text with <f ont> and <del > tags. However, that 
approach has two distinct disadvantages: 

♦ The <f ont> tag has been deprecated and should not be used. 

♦ If you later change your mind about the color or decoration (strikethrough), 
you would have to find and change each set of tags. 

Instead, define a style for the elements that contains the desired text attributes. The 
following HTML code snippet defines such a style and uses it to highlight a sentence 
later in the document: 



(html) 
(head) 
<style) 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 23 



</st 
/head 
body) 
hl>An 
p>Whe 
or on 
onnec 
f the 
aws o 
espec 
eel ar 
1 ass = 
auses 
/body 
/html 



e d 1 i n e 
yle> 



color: red; text -decorati on : 1 i ne -through ; 



Early Draft of the Declaration of Independence</hl> 
n in the Course of human events, it becomes necessary 
e people to dissolve the political bands which have 
ted them with another, and to assume among the powers 

earth, the separate and equal station to which the 
f Nature and of Nature's God entitle them, a decent 
t to the opinions of mankind requires that they should 
e the causes which impel them to the separation. <span 

redl i ne">Thi s document declares those 

</span></p> 



This code results in the output shown in Figure 2-2. 



'^] litt|> : ■'. I ■> c ,1 1 h >sT. sail i |j I e .luiu I - Mi c i )soft I lit* i net E x p 1 01 e i 



"EBB 



File Edit View Favorites Took Help 



a-e-aiol^t*© - & ^ -a 



Address | ffi http : //bcdhost/sample , html 



Mmi 



An Early Draft of the Declaration of Independence 

When m the Course of human events, it becomes necessity for one people to dissolve the political hands which have 
connected then, with another, and to assume among the powers of the earth, the separate and equal station to which the Laws 
cf Matuie aijd <jf ITaUue's Gud eciUlle lliem, a decent iespect lu llie opinions of mankind iequues Lhit Lhev shy lid dcclaic Lie 
causes which impel them to the separation. Thi s docum e n t d e clar es tho se cau ses . 

Figure 2-2: The "redline" style is applied to applicable text via the <span> tag. 






Note 



Styles can also be applied directly to many HTML tags using the style attribute. 
For example, to apply the red and strikethrough attributes to an entire para- 
graph, you could use the following code: 



<p styl e="col or : red; text -decorati on : line- 
through;") sample paragraph </p> 

However, using styles in this manner removes many of the easily modified 
advantages gained by using styles. 

If you later needed to change the text attributes, one edit in the <sty 1 e> section of 
the document would affect the change throughout the document. But what if you 
had several documents that used the style? You would still have to edit each 
document to make the style change. Luckily, HTML's style implementation allows for 
external style sheets that can be applied to multiple documents — then you only have 
to change the external style sheet. 



PI: JYS 

WY022-02 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Part I 4 Understanding (X)HTML 



The following code defines site-styles. ess as an external style sheet in the 
current HTML document: 



<html> 

<head> 

<LINK rel="styl esheet" href="si te -styl es . ess' 

type="text/css"> 

</head> 

<body> ... 



The contents of the site-styles. ess document would be the definitions that you 
would have placed between the <style> tags. For the preceding redline example, the 
contents of this file could simply be the following: 

.redline { color: red; text-decoration: line-through; 1 



Cross- , There are many more attributes that can be applied to text and other objects 




Reference 



via styles. You'll find more details on styles in Chapter 16. 



Block Elements: Markup for Paragraphs 

As with most word processors, HTML includes several tags to delimit, and hence, 
format paragraphs of text. These tags include the following: 



4- < p > — Formatted paragraphs 

♦ < h 1 > through < h 6 > — Headings 

4 <blockquote> — Quoted text 

4 < p r e > — Preformatted text 

4 <ul >,<ol >, <dl > — Unnumbered, ordered, and definition lists 

4 <center> — Centered text 

4 <di v> — A division of the document 



Each of the block elements results in a line break and noticeable space padding after 
the closing tag. As such, the block elements only work when used to format 
paragraph-like chunks of text — they cannot be used as inline styles. 

More detail about each of these tags is covered in the following sections. 

Cross- \ You'll find more details on block elements and their formatting in Chapter 4. 
Reference 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



Formatted paragraphs 



The paragraph tag (<p>) is used to delimit entire paragraphs of text. For example, 
the following HTML code results in the output shown in Figure 2-3: 

<p>The quick brown fox jumped over the lazy dog. The quick 
brown fox jumped oven the lazy dog. The quick bnown fox 
jumped oven the lazy dog. The quick bnown fox jumped oven the 
1 azy dog . </p> 

<p>The quick bnown fox jumped oven the lazy dog. The quick 
bnown fox jumped oven the lazy dog. The quick bnown fox 
jumped oven the lazy dog.</p> 



i v , Imp: hc.illi>5t &<iih|ile.html - Microsoft Internet Expiorei 



TZIaBl 



File Etlit View Favorites Took Hel|> 



Address ,,. , http : tf bcdhost/ sample . html 



It 



The quick brown fox jumped sver the lazy dog. The qui;k brown foxjurr.ped ever the lazy dog. The quick brovm fox jumped 
ever the lazy dog. The quick brovm fox jumped over the lazy dog. 

The quick brovm foK jumped ever the lazy dog. The quick brown foK jurr.pcd ever the lazy dog. The quick broivnfon jumpco 
ever the lazy dog. 

Figure 2-3: Paragraph tags break text into distinct paragraphs. 



As with most tags, you could define several formatting elements (font, alignment, 
spacing, and so on) of the <p> tag. For example, you can center a paragraph by 
adding an a 1 i g n attribute to the < p > tag: 

<p al i gn="centen"> The quick bnown fox jumped oven the lazy 
dog. The quick bnown fox jumped oven the lazy dog. The quick 
bnown fox jumped oven the lazy dog.</p> 

However, such formatting has been deprecated in favor of specifying formatting via 
style sheets. The following is an example of using style sheets to achieve the same 
results as the align attribute: 



dog 

b 
</ 
</ 



tml> 

ead> 
tyle 
cent 
styl 
head 
ody> 
cl a 
T 
nown 
body 
html 



type="text/css"> 
en {text-align: centenl 
e> 



ss="centen"> The quick bnown fox jumped oven the lazy 
he quick bnown fox jumped oven the lazy dog. The quick 
fox jumped oven the lazy dog.</p> 



PI: JYS 

WY022-02 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



26 Part ' ♦ Understanding (X)HTML 



Using either of the preceding methods results in the paragraph being center-justified 
in the browser. 



Headings 



HTML supports six levels of headings. Each heading uses a large, usually bold 
character-formatting style to identify itself as a heading. The following HTML 
example produces the output shown in Figure 2-4: 



;idocty 

"htt 
;body> 
;hl>Hea 
;h2>Hea 
;h3>Hea 
;h4>Hea 
;h5>Hea 
;h6>Hea 
; p > P 1 a i 
;/body> 
;/html> 



PE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
p://www.w3.org/TR/htnil4/strict.dtd"> <htmi: 



di 



ng K/hl> 

ng 2</h2> 

ng 3</h3> 

ng 4</h4> 

ng 5</h5> 

ding 6</h6> 
n body text: 



The quick brown fox jumped over the lazy dog.</p> 



|^J littpi/'/localhost'sam pie. html - Microsoft Internet Explorer 


UoH 


File Edit View Favorites Tools Hel|> 


& 


o-i> s m <& \P ^»e @'SB4 



AriHrsw | ^\ http : //loc^host/sampJe . html 












UB' 


Heading I 














Heading 2 














Heading 3 














Heading 4 














Healing S 














Heubifo 














Plan hody text Trip quirk ^r^wti 


Fc.-x 


j" imped 


otfet 


t.h= 


h?y dog 





*J Local intranet 



Figure 2-4: HTML supports six levels of headings. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



The six levels begin with Level 1, highest, most important, and go to Level 6, the 
lowest, least important. Although there are six predefined levels of headings, you 
probably will only find yourself using three or four levels in your documents. Also, 
because there is no limit on being able to use specific levels, you can pick and 
choose which levels you use — you don't have to use <hl> and <h2> in order to be 
able to use <h3>. Also, keep in mind that you can tailor the formatting imposed by 
each level by using styles. 

Styles are covered in Chapter 16. 




Quoted text 



The <bl ockquote> tag is used to delimit blocks of quoted text. For example, the 
following code identifies the beginning paragraph of the Declaration of 
Independence as a quote: 



<body> 
<p>The D 
<bl ockqu 
When in 
one peop 
connecte 
of the e 
Laws of 
respect 
decl are 
</bl ockq 
</body> 



eclaration of Independence begins with the following paragraph:</j 

ote> 

the Course of human events, it becomes necessary for 

le to dissolve the political bands which have 

d them with another, and to assume among the powers 

arth, the separate and equal station to which the 

Nature and of Nature's God entitle them, a decent 

to the opinions of mankind requires that they should 

the causes which impel them to the separation. 

uote> 



The <bl ockquote> indents the paragraph to offset it from surrounding text, as 
shown in Figure 2-5. 



htt|>: lociilhost $<im|:<le.litml -Mkiosoft Internet Ex|ilom 



D&yi 



File Edit View Favorites Tools Hel|> 



fr 



Address \jg\ hitpij/localhost/sarmple.htrnl 



Tila< 



The Declaration of Independence begins with the following paragraph 

"When in the Course of human events, it becomes necessary for one people to dissolve ths political bands which 
have connected them w.th another, and to assume among the powers of the earth, the separate and equal station 
to which the Laws of Nature and of Nature's God emitle them, a decent respect to the opinions of mankind 
requires that they should declare the ;auses which impel them to the separation. 



Figure 2-5: The <bl ockquote) tag indents the paragraph. 



*l 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Understanding (X)HTML 

List elements 

HTML specifies three different types of lists: 

♦ Ordered lists (usually numbered) 

♦ Unordered lists (usually bulleted) 

♦ Definition lists (list items with integrated definitions) 

The ordered and unordered lists both use a list item element (<1 i >) for each of the 
items in the list. The definition list has two tags, one for list items (<dt>) and 
another for the definition of the item (<dd>). 

The following HTML code results in the output shown in Figure 2-6. 

<html> 
<body> 
<ol>A basic ordered list 

<li>First ordered item 

<li>Second ordered item 

<li>Third ordered item 



g] http ://! q ca I host/Ch a ptert)2/F ig0206.htm I Microsoft Internet Explorer 



Q(5]Q 



File Edit View Favorites Tools Help 



O-d-ES^ P & * © 0-&S& 



Address 



| http : //Iocalhost/Chapter02/Fig0206 , html 



Go 



A basic ordered list 

1. First ordered item 

2 . S e c ond ordere d item 

3. Third ordered item 

Unordered list 

• First unordered item 

• S e c ond unordere d item 

• Third unordered item 

Definition list 
First definition item 

First definition 
Second definition item 

Second definition 
Third definition item 

Third definition 



Done 






*J Local intranet 



Figure 2-6: A sample list in HTML. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



</ol> 
<ul>Unordered list 

<li>First unordered item 

<li>Second unordered item 

<li>Third unordered item 
</ul> 
<dl >Deflni ti on list 

<dt>First definition item 

<dd>First definition 

<dt>Second definition item 
<dd>Second definition 

<dt>Third definition item 

<dd>Third definition 
</dl> 
</body> 
</html> 

Because of the amount of customization allowed for each type of list, you can create 
many substyles of each type of list. For example, you can specify that an ordered list 
be ordered by letters instead of numbers. The following HTML code does just that, 
resulting in the output shown in Figure 2-7. 

<html> 
<body> 
<ol styl e="l i st-styl e : 1 ower-al pha ; ">A basic ordered list (lower-case alpha) 

<li>First ordered item 

<li>Second ordered item 

<li>Third ordered item 
</ol> 
</body> 
</html> 



■- litt|>: l>callv>sTs<im|jle.hTml - Micr>soft Internet Exploiei 



•^so 



Filfs F «"■ ir Vi^w Favorites Tfirtls Hsl|> 

O ' O - if] is] 6 I P ts « © I & - 



m % 



hLLp;//luLdliuiL/idiii|Je.liLiiil 



"BE' 



Abaac ordered list (lower-case alpha) 

a. First ordered rem 

b. Second ordered item 
r. Third order=ditem 



Figure 2-7: Using various list styles, you can customize each list in your document. The list 
shown uses the list-style lower-alpha. 



Note 



Older versions of HTML allowed various list options to be specified in the list 
tag(s). However, current versions of strict HTML and XHTML formats specify that 
all list options be contained within styles. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Part I ♦ Understanding (X)HTML 



Preformatted text 

Occasionally, you will want to hand format text in your document or maintain the 
formatting already present in particular text. Typically, the text comes from another 
source — cut and pasted into the document — and can be formatted with spaces, tabs, 
and so on. The preformatted tag (<p re>) causes the HTML client to treat white 
space literally and not to condense it as it usually would. 

For example, the following table will be rendered just as shown below: 



*pre) 



val ue 



wsupdate 

1 easeupdate 
1 f status 
edupdate 



1069009013 

Wed, 8/28, 8:18pm 



1069009861 



C/pre) 



Divisions 

Divisions are a higher level of block formatting, usually reserved for groups of 
related paragraphs, entire pages, or sometimes only a single paragraph. The division 
tag (<di v>) provides a simple solution for formatting larger sections of a document. 
For example, if you need a particular section of a document outlined with a border, 
you can define an appropriate style and delimit that part of the document with 
<d i v> tags, as in the following example: 



html) 
head) 

<style 
. bor 

</styl 
/head) 
body) 
p > T h i s 
d i v c 1 a 
he defin 
/body) 
/html) 



dered 
e> 



border-sty le: solid; I 



is a normal paragraph. </p> 

ss= " bordered "><p>Th is is a paragraph delimited with 

ed d i v style which includes a border . </p)</di v) 



This code results in the output shown in Figure 2-8. 




Cross- For more information on how to format blocks of text with the <di v> tag, see 

Reference, chapter 16 . 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



htt|>: -"Jociilhosf Hdini'le.luiiil -Mitio^oft Internet Ex|)lom 



1311a 



File Edit: View Favorites Tools Help 

o-o-aatt|iP-M-#«|si' 



Address \^\ h=l=p:j/lQi:3lhQ5l=/sample,htrnl 



13H< 



This is £ normal paragraph. 



Int is i paragraph delriiiLed will. Llic defined div sLyle wluuli muludei a buiiei 



Figure 2-8: <div> tags are used to delimit large sections of text. 



Inline Elements: Markup for Characters 

The finest level of markup possible in HTML is at the character level; just as in a 
word processor, you can affect formatting on individual characters. This section 
covers the basics of inline formatting. 



Basic inline tags 

Inline formatting elements include the following: 

♦ Bold(<b>) 

♦ Italic (< i >) 

♦ Big text (<big>) 

♦ Small text (< s ma 1 1 >) 

♦ Emphasized text (< em >) 

♦ Strong text (< strong >) 

♦ Teletype (monospaced) text (<tt>) 

For example, consider the following sample paragraph, whose output is shown in 
Figure 2-9. 

<html> 

<body> 

< p > T h i s paragraph shows the various inline styles, such as 

<b>bold</b>, <i>ital ic</i>, <big>big text</big>, <small>small 

text</sma 1 1 > , <em>emphasi zed text</em>, <strong>st rong 

text</strong> , and <tt>teletype text</tt> . </p> 

</body> 

</html> 

Note that several inline tags, such as strikethrough (<stri ke>) and underline (<u>) 
tags, have been deprecated in the current specifications. Even the font tag (<f ont>) 



PI: JYS 

WY022-02 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



32 Part I ♦ Understanding (X)HTML 



'. hlt|>: ■'! o c n I h ost-"Sii m |> I e . lit m I -Mkiosoft Internet E>;|iloiei 



~ssm 



File EcliT View Favorites Tools Help 

o - o a © &\ p * * e I £ - & ip -& 



Address |||] h:l:p : j/localhosb/sample . html 



^B< 



This paragraph shows the various inline styles, ;uch as l>ol<l, italic, bur text, small -.ext ; emphasized text, stion^ text, and 
teletype text 



Figure 2-9: Inline elements can affect words or even individual characters. 



has been deprecated in favor of spanning styles (see the Spanning section later in 
this chapter). As for the strikethrough and underline tags, they have been replaced 
by delete (<del >) and insert (<i ns >), which are used for revisions (delete for 
deleted text, insert for inserted text). 

Cross- More information on inline elements is contained in Chapter 4. 

Reference 




Spanning 



Spanning tags (<span>) are used to span inline styles across multiple characters or 
words . In effect, the <span> tag allows you to define your own inline styles . For 
example, if you need to specify text that is bold, red, and underlined, you could use 
code similar to the following: 

<html> 
<head> 
<style> 

.emphasis { color: red; text-decoration: underline; 
font- weight: bold; 1 
</style> 
</head> 
<body> 
<p><span cl ass="emphasi s">Thi s text is emphasi zed</span> , 

while this text is not.</p> 
</body> 
</html> 

The < s p a n > tag allows you to apply the stylistic formatting inline, exactly where you 
want it. 



Special Characters (Entities) 



Some special characters must be referenced directly instead of simply typed into the 
document. Some of these characters cannot be typed on a standard keyboard, such 
as the trademark symbol (™) or copyright symbol (©); others could cause the 
HTML client confusion (such as the angle brackets, < and >). Such characters are 
commonly referred to as "entities." 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 33 



Entities are referenced by using a particular code in your documents. This code 
always begins with an ampersand (&) and ends with a semicolon. Three different 
ways to specify an entity exist: 

4- A mnemonic code (such as copy for the copyright symbol) 

♦ A decimal value corresponding to the character (such as #169 for a copyright 
symbol) 

♦ A hexidecimal value corresponding to the character (such as #xA9 for a 
copyright symbol) 

Note that if you use the decimal or hexadecimal methods of specifying entities, you 
need to prefix the value with a number sign (#). 

The following are all examples of valid entities: 

♦  — A non-breaking space (see later) 

♦ < — The less-than symbol, or left-angle bracket (<) 

♦  — The copyright symbol (©) 

♦ & — An ampersand (&) 

♦ &#151;— An em dash (— ) 

Cross- % You'll find more information on entities in Chapter 9. 
Reference 




Inappropriate Entity Use 



One particular entity, the nonbreaking space, is often used and abused to add white space 
to HTML documents. For example, to add a larger gap between paragraphs, the following 
code is often used: 

<p>&nbsp ; </p> 

This code results in a blank paragraph— without the space, most browsers will not render the 
paragraph because it is empty. 

However, that is not the intent of this entity— it is meant to keep words from being split 
between rows of text. Using it to add white space is not recommended. Instead, use styles 
as directed in the various sections of this book. 



Organizational Elements 



Two HTML elements help organize information in a document: tables and forms. 
Tables allow you to present data in column and row format, much like a spreadsheet. 
Forms allow you to present (and retrieve) data using elements common to GUI 
interfaces — elements such as text boxes, check boxes, and lists. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Understanding (X)HTML 



Tables 

HTML tables are very basic, but can be very powerful when used correctly. At their 
base level, tables can organize data into rows and columns. At their highest level, 
tables can provide complicated page design — much like a page in a magazine or 
newspaper, providing columns for text and sections for graphics, menus, and 
so on. 

Tables have three basic elements and, hence, three basic tags: 

♦ The table definition itself is defined and delimited by <ta bl e> tags. 

♦ Rows of data are defined and delimited by <t r> (table row) tags. 

♦ Table cells (individual pieces of data) are defined and delimited by <td> 
(table data) tags. Table cells, when stacked in even rows, create table 
columns. 

For example, consider the following code, which results in the output shown in 
Figure 2-10: 



html) 

body) 

table border="l"> 
<tr><td>Name</tdXtd 
td>Angela</td>< 
td>Branden</td> 
td>Doug</td><td 
td>Ian</td><td> 
td>Jeff</tdXtd 
td>John</tdXtd 
tdXeitX/tdXt 
td>Michael</td 
td>Steve</td><t 
t 



<tr 

<tr 

<tr 

<tr 

<tr 

<tr 

<tr 

<tr 

<tr 

<tr 
C/table 
(/body) 
;/html> 



td>Steven</td 



>Age 
td>3 
<td> 
>23< 
31</ 
>34< 
>33< 
d>39 
td> 
d>38 
td>4 



td>< 

/td; 

</tc 

dX 

></ 



td> 
</t 
td> 
/td 



It 
</ 
X 

/tr) 
tr> 

/tr) 

/tr) 

</tr 

dX 

</t 

></ 



tr> 

/tr) 



/tr) 

r> 

tr> 



This example is very straightforward because the table is very simple. However, due 
to the number of options you can use in formatting table elements and the fact that 
you can nest tables within tables, the tables in your HTML documents can get very 
complicated (and very powerful). To illustrate this point, compare Figures 2-11 and 
2-12. Figure 2-11 shows a page as it normally appears in the browser. However, if you 
turn on the table borders you can see how several tables (and nested tables) are 
used to provide the document layout, as shown in Figure 2-12. 




Cross- 
Reference 



Tables are covered in detail in Chapter 10. Using tables for page layout is covered 
in Chapter 1 1. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



\^\ htt|> ://l o cfi I h -ost-'sn ni|>l e . htiii I - Microsoft Internet Explorer 
File Ed It View Favorites Tools Help 



\=}\sm 



ArlHte^ \^\ ittp : //locahost/samiile . ntm 



~®B< 




^Cone 

Figure 2-10: Eleven rows and two columns of data in a table. 



*J LDcal intranet 



\^\ PiinchtlieBnjj - Microsoft Internet Explorer 
File E<IIt View Favorites Tools Hel|> 

D r* O - I I O P * * © 



yt£jsai 



i- ^ s ^ 



Arlrhp« ^) ittp : //www . pLnthtkeb^g com/ 



BE' 




PUHCIITUt 13 A G 

t^iqar5 T M annartans h and Omall I air 



_>pik^d Punch 

19 Mcvcmbcp- 2003 



Steve Hammers An Alzheimer Patient 

4 0j 3.D. dt 2.0 3 D A it doesn't natter. Co lege students a _ e just kics. 
CDisidcr :hcm business s:ort-i_ps; with angel investors (parents) 
Dropping :hern up with thousands if not tons of:hcusands of dollars 
with the hnnp that ^rrnerl^y they'll gn p jhhr. Tt'q f hit nerve cranking, 
ike ouyhg a corvette ""cr a <id after he g-acuates frorr surnme- diving 
i.uhuul, 

Even thouqh triers ere colleqe s:ucents ss:tinq Furniture on fire after 
football games, drinking and crivirg and gs:ting -dlled, dealing in drugf, 
5ts=IHg, and othor stuff that we do our test te tu-n a blind eye to, 
BtQVQ Hamn-Er ct Nlvq i^ cutraged over =n Indiara University Collggg 
-iepublican take sale. I'm not here to defenc :he sake sale prank. 



J} Internet 



Figure 2-11: This document uses invisible tables to achieve its layout. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



6 Part I ♦ Understanding (X)HTML 



\^\ PunchlheBLij - Microsoft Internet Explorer 
File E<IIt View Favorites Tools Help 

©■* © a in p t? * e 



3 ' & 13 .& 



i . pLnchtheb=q corTi/i^bl^-e^aTiDts^hhyJ 



S 




P U fl C h T H E BA G 

l jinai s. M nrhnttnrs. nnrl ^mnll I nit 



JpiKed Punch 



19|n u yL-i.iUr.|a|C)l0"^"| 



In the jhak< 



- f 


Reac 'Story" to Lean 


Story 


-f 


WhII (tnlly Cpf>. Ft=phiH 



Steve Hammers An Alzheimer Patient 

1 0j 3.D. or 2.0 C^A it doesn't natter. Co lege students ire just kics. 
CD-isidar :hern bu=ina££ =:art-i_ps with angal invastors (parents) 
nrnfpinr -hFrn up with thnu^^nriq it nnt renq nt -Viru^^nri^ nr rJ-illar=; 
with the hope that scrnedEy they'll go pjblic. it's e bit nerve wracking, 
\h.ti Liuvi" il| d Curvy Lit ~i_r d <iU dftbr he L|dLUdtbi frurr iurrnriy Uivinui 
school, 



Zven though there ere college 5:ucents 5e:ting Furniture on fire after 
football games, drinking and crivirg and ga:ting -dllod, doaling in drugs, 
storing, and othor stuff that wq do our test to turn a blind eye to, 
=:teve Harnn-Er cf nlvo is cutfeqed over an Jndiara univ ersity college 

tip Internet 



Figure 2-12: Making the table borders visible shows just how many tables are 
involved in laying out the page and how they help constrain the layout. 

Forms 

HTML forms provide a method to use standard GUI elements to display and collect 
data. HTML forms provide the standard litany of GUI elements, including text boxes, 
check boxes, pull down (also referred to as drop-down) lists, and more. In addition 
to providing basic GUI elements, HTML forms also provide a rudimentary method of 
collecting data and passing that data to a data handler for validation, storage, 
comparison, and so on. 

A typical HTML form resembles the following code, the output of which is shown in 
Figure 2-13. 



Chtml> 

(body) 
(form) 

<! -- Text field --> 

<b)Name:</b> <input type 

<br)<br> 

< ! - - Radio buttons - - > 

<b>Age:</b> 

<input type="radio 
<input type="radio 
<input type="radio 
<input type="radio 



="text" naine="naine" size="4C 



name= age 
name="age' 
name="age' 
name="age' 



21 
31 
41-1 



30 
40 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



<br><b 


r> 


<!-- S 


el ec 


<b>Wha 


t i s 


<sel 


ect 


<o 


oti o 


<o 


Dti 


<0 


oti o 


</se 


1 ect 


<br><b 


r> 


<!-- Check 


<b>How 


may 


< i n p u t 


typ 


< i n p u t 


typ 


< i n p u t 


typ 


< i n p u t 


typ 


/form) 




/body) 




/html) 





t list --> 
your favorite ice cream?</b> 
name="i cecream") 
n name="chocol ate">Chocol ate 
n name="st rawberry">St rawberry 
n name="vani 1 1 a">Vani 1 1 a 



boxes --> 

we contact you for more i nf ormati on?</b><br> 
e="checkbox" name="phone">Phone<br> 
e="checkbox" name="mai 1 ">Mai 1 <br> 
e="checkbox" name="ema i 1 ">Emai 1 <br> 
e="checkbox" name="no">Do not contact me<br> 



:' '. Irttp: 1 Mj/tlLriyt 'i/iiii|.i|A.hiinl . Microsoft Internet Explorer 


Lkyi 


File Edit View Favorites Tools Hel|> 


* 


o - © - b s & /> &• • -a \s - a m % 



Adtfreis |g] ht:p //bcalhost/samcle.ht-nl 



BB' 



Name 



Age: O <2U © ai — 3ti C jl-40 O 41+ 
What is yam favoiTte ice cream? | Chjcoalc |v| 

Hjcnvmay we contTKtyou for more information? 

DPliojie 

□ Mail 

niimail 

DI>o not contact me 



Figure 2-13: Form elements provide standard GUI controls for displaying and collecting 
data. 



The preceding example form is very simple, it shows only some basic elements, and 
has no handler to process the data that is collected by the form. Real-world forms 
can be quite complex and usually require validation scripts to ensure the data 
collected is valid. However, this simple form illustrates the amount of control you 
can assert over data and format using HTML. 

Cross- \ Forms are covered in detail in Chapter 13. 
Reference 




Linking to Other Pages 



The main advantage to the World Wide Web is the ability to link to other documents 
on the Web. For example, if you had a page that detailed local zoning laws, you might 



PI: JYS 

WY022-02 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



8 Part I ♦ Understanding (X)HTML 



want to include a link to a local government site where additional information could 
be found. A link typically appears as underlined text and is often rendered in a 
different color than normal text. 

For example, a link might appear in a browser as follows: 

More information can be found here. 

The word here is linked to the other document — when the user clicks the word, the 
user's browser displays the specified page. 

Create links by using the anchor tag, <a >. At its simplest level, this tag takes one 
argument — the page to link to — and surrounds the text to be linked. The preceding 
example could be created with the following code: 

More information can be found 

<a href="http: //www.whi tehouse .gov">here</a> 

The h ref , or Hypertext REFerence attribute of the anchor tag, specifies the protocol 
and destination of the link. The example specifies http : / / because the destination 
is a Web page to be delivered via the HTTP protocol. Other protocols (such as 

ftp : // or mai 1 to :) can also be used where appropriate. 

Additional attributes can be used with the anchor tag to specify such things as 
where the new document should be opened (for example, in a new browser window), 
the relationship between the documents, and the character set used in the linked 
document. 

You can also use a variant of the anchor tag to mark specific places in the current 
document. A link can then be placed elsewhere in the document that can take the 
user to the specific place. For example, consider this HTML code: 

For more information see <a href="#Chapt2">Chapter 2</a> 

. . . More HTML ... 

<a name="Chapt2">Chapter 2</a> 

In this example, the user can click the Chapter 2 link to move to the location of the 
Chapter 2 anchor. Note that the href link must include the hash symbol (#), which 
specifies that the link is an anchor instead of a separate page. 

- Cross- More information on links and anchors can be found in Chapter 7. 

Reference 



Images 



One of the great innovations the World Wide Web and HTTP brought to the Internet 
was the ability to serve up multimedia to clients. The precursors to full-motion video 
and CD quality sound were graphical images, in the Web-friendly Graphics 
Interchange Format (GIF) and Joint Photographic Experts Group (JPEG) formats. 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



You can include images in HTML documents by using the image tag (<i mg>). The 
image tag includes a link to the image file as well as pertinent information used to 
display the image (for example, the image size). A typical image tag resembles the 
following: 

<img src="/images/tmoore. jpg" alt="A picture of Terri" 
width="100" height="200"> 

The preceding example would result in the image tmoo re .jpg being displayed at 
the location in the document where the tag appears. In this case, the image is in the 
i mages directory of the current server and will be displayed without a border, 
100 pixels wide by 200 pixels high. The a 1 1 attribute is used to provide a textual 
equivalent for browsers that cannot display graphics (or whose users have 
configured them not to). 

Images can also be used as navigation aids — allowing the user to click certain parts 
of an image to perform an action, display another document, and so on. For example, 
a map of the United States could be used to help a user select their state — clicking a 
state would bring up the applicable page for that state. Navigational images are 
commonly referred to as image maps and require a separate map of coordinates and 
geometric shapes to define the clickable areas. 




You'll find more information on images in Chapter 6. 



Comments 



Although HTML documents tend to be fairly legible, there are several advantages to 
adding comments to your HTML code. Some typical uses for comments include 
aiding in document organization, document specific code choices, or marking 
particular document sections for later reference. 

HTML uses the tag < ! - to begin a comment and - > to end a comment. Note that the 
comment can span multiple lines, but the browser will ignore anything between the 
comment tags. For example, the following two comments will both be ignored by the 
browser: 

<!-- This section needs better organization. --> 



and 



!-- The Tollowing table needs to include these columns: 
Age 

Marital Status 
Employment Date 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



40 



Part I ♦ Understanding (X)HTML 



Scripts 



HTML is a static method of deploying content — the content is sent out to a client 
browser where it is rendered and read, but it typically doesn't change once it is 
delivered. However, there is a need in HTML documents for such things as 
decision-making ability, form validation, and, in the case of Dynamic HTML (DHTML), 
dynamic object attribute changes. In those cases (and more), client-side scripting 
can be used. 




Note 



For more information on client-side scripting, see Chapter 15. 



Client-side scripting languages, such as JavaScript, have their code passed to the 
client browser inside the HTML document. It is the client's responsibility to interpret 
the code and act accordingly. Most client-side scripts are contained in the <head> 
section of the HTML document, within < s c r i p t > tags, similar to the following 
example: 

<html> 
<head> 

<script 1 a nguage=" Java Script") 
function Mi scWi ndow( w, h , url ) { 
opts = "wi dth="+w+" , hei ght="+h ; 
opts = opts+" , scrol 1 ba rs=no , resi zabl e=yes" ; 
fin=window.open(url ,"",opts) ; 
) 
</script> 
</head>. . . 

In most cases, the document needs to include events to run the script(s). These 
events can be embedded in elements (via onmouseover or similar attributes), tied 
to links, called via form elements, or run upon the document being loaded or 
unloaded (via onload and onunl oad attributes in the <body> tag). 

There are methods to run scripts automatically, that is, without a corresponding 
event. However, such methods are typically thought of as bad form— it is much 
better practice to always tie a script's execution to an event. 



Putting it All Together 



As you can see, the standard HTML document is a fairly complex beast. However, 
when taken piece by piece, the document becomes just like any other HTML 
document. The following HTML listing shows how all of these pieces fit together. 



C ! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/stnict.dtd"> <html> 
(head) 

<meta . . . meta tags go here ... > 

<title> title of the page/ document goes ftere</title> 



PI: JYS 
WY022-02 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



Chapter 2 ♦ What Goes Into a Web Page? 



< L I N K rel ="styl esheet" href="external style sheet name" 

type="text/css"> 
<style> 

... any document specific styles go here ... 
</style> 
<scri pt> 

... client-side scripts go here ... 
</script> 
<body> 

. . . body of document goes here, paragraphs modified by 
block elements, characters, words and sentences modified by 
in 1 i ne el ements . . . 
</body> 
</html> 

All HTML documents should have a <D0CTYPE> specification, <html > and <body> 
tags, and at least a <ti tl e> within the <head> section. The rest of the elements are 
strictly optional, but help define the documents' purpose, style, and ultimately its 
usability, as you will see in the following chapters. 



Summary 



You have seen what basic elements make up an HTML document. Although the 
amount of elements may seem daunting at first, you will quickly learn what purpose 
each element serves, how it affects other elements in the document, and how to best 
use each element to construct the best HTML document for your purpose. As you 
read about the elements in more detail — within the next few chapters — try to match 
their capabilities against your needs. 



From here, you should read Chapters 3 through 24 to extend your understanding of 
the various elements of HTML. Alternatively, jump to specific chapters that cover 
elements that interest you, or that you don't completely understand. (Follow the 
various cross-references in each section in this chapter to find the relevant chapter 
to the specific element you wish to learn more about.) 



PI: JYS 

WY022-02 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:38 



42 



PI: JYS 
WY022-03 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



Starting Your 
Web Page 



Now that you know more about the background 
of HTML and the types of elements involved in an HTML 
document, it's time to delve into the particulars of each 
element. This chapter covers more specifics of the basic 
elements and starts to show how easy it is to manipulate 
HTML to create impressive documents. 



Basic Rules for HTML Code 

Creating HTML documents is actually quite easy — HTML 
documents are simply text files embedded with HTML 
commands. You can create the documents with any editor 
capable of exporting raw text. In addition, HTML browsers are 
very forgiving about white space — additional tabs, line feeds, 
or spaces don't matter. 

As you create your first few HTML files, it is important to start 
using some good coding habits, habits that will serve you well 
as you code more complex pages later on. For example, 
consider the practices outlined in the following sections. 



Use liberal white space 

Insert liberal line breaks to separate code sections, and use 
spaces to indent subsequent elements. Both of these will help 
you read and understand your code. Consider the following 
two code samples: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/htnil4/strict.dtd"> 
<html> 
<head> 

<title>The Declaration of Independence</title> 
<meta name="descri pti on" content="0ur Nation's 
Declaration of I ndependence"Xmeta name="keywords" 
content="declaration, independence. 




In This Chapter 

Basic Rules for HTML Code 
Creating the Basic Structure 
Declaring a Document Type 












Specifying a Document Title 

Providing Information to 
Search Engines 

Setting the Default Path 

Creating Automatic 
Refreshes and Redirects 

Page Background Color 
and Background Images 




43 



PI: JYS 
WY022-03 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



44 Part I ♦ Understanding (X)HTML 



revolutionary, 


war , 


July, 4, 


Declaration of 


Inde 


Dendence< 


1776.</pXp>The 


unanimous De 


of the thirteen 


uni 


ted State 


Course of human 


events, it b 


to dissolve the 


pol 


i t i c a 1 b a 


with another, and t 


o assume 


the separate an 


d eq 


u a 1 s t a t i 


and of Nature's 


God 


entitle 


opinions of man 


<i nd 


requires 


causes which i m 


Del 


them to t 


these truths to 


be 


s e 1 f - e v i d 


created equal , 


that 


they are 


certain unalienable 


Rights, 


Liberty and the 


pursuit of H 



1776"X/headXbodyXhl>The 
/hlXpMN CONGRESS, July 4, 
c 1 a r a t i o n 

s of America,</pXp>When in the 
ecomes necessary for one people 
nds which have connected them 
among the powers of the earth, 
on to which the Laws of Nature 
them, a decent respect to the 

that they should declare the 
he separation.</p> <p>We hold 
ent , that al 1 men a re 

endowed by their Creator with 
that among these are Life, 
a p p i n e s s . . . 



and 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html><headXtitle>The Declaration of 

Independence</t i tl eXmeta name="descri pt i on" content="Our 
Nation's Declaration of Independence") 

<meta name="keywords" content="decl arati on , independence, 
revolutionary, war, July, 4, 1776") 
</head><body> 

<hl>The Declaration of I ndependence</hlXp>I N CONGRESS, July 
4, 1776. </p> 

<p>The unanimous Declaration of the thirteen united States of 
America , </pXp>When in the Course of human events, it becomes 
necessary for one people to dissolve the political bands 
which have connected them with another, and to assume among 
the powers of the earth, the separate and equal station to 
which the Laws of Nature and of Nature's God entitle them, a 
decent respect to the opinions of mankind requires that they 
should declare the causes which impel them to the 
separati on . </pXp>We hold these truths to be self-evident, 
that all men are created equal, that they are endowed by 
their Creator with certain unalienable Rights, that among 
these are Life, Liberty and the pursuit of Happiness. . . 

As you can tell, the second example is much easier to read and, hence, easier to 
troubleshoot. 



Use well-formed HTML 



Well-formed HTML means that your documents need to have the following 
characteristics: 



♦ Contain a <D0CTYPE> tag. 

♦ Elements must be nested, not overlapping. This means that you need to close 
elements in the opposite order of how they were opened. For example, the 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



Chapter 3 ♦ Starting Your Web Page 4 



following example is wrong: 

<p>The last word is <b>bol d</p></b> 

Note how the bold and paragraph tags overlap at the end of the block. Instead, 
the bold tag should have been closed first, as in the following example: 

<p>The last word is <b>bol d</b></p> 

♦ Element and attribute names must be in lowercase. XHTML is case-sensitive; 
the tag <H R> is different from the tag <h r>. All the tags in the XHTML 
Document Type Definitions (DTDs) are lowercase — so your documents' tags 
need to be, as well. 

4- All non-empty elements must be terminated. For example, the following is not 
allowed: 

This is one paragraph<p>Thi s is another paragraph<p> 

Instead, each open paragraph tag needs to be closed. 

♦ All attribute values must be quoted. For example, consider the two following 
tags: 

<table border=0> 

and 

<table border="0"> 

The first tag is incorrect because the attribute value is not quoted. The second 
is correct because the attribute is correctly quoted. 

4- You cannot use minimized attributes, that is, attributes without values. For 
example, consider the two following tags: 

<input type="checkbox" checked) 

and 

<input type="checkbox" checked="checked"> 

The first tag has a minimized attribute; the checked attribute is named but has 
no value. 

♦ Any empty tag must have a closing tag or the opening tag must end with a slash 
(/). For example, consider the <h r> tag, which doesn't have a closing tag. As 
such, it should always appear with an ending slash, <h r / >. 



Comment your code 



Well-written code should speak for itself. However, there are plenty of instances 
when including comments in your code is warranted. For example, in Chapters 22 
and 23, you will learn how to use nested tables to create complex textual layouts. 
However, such constructs often result in code such as the following: 



</table) 

</table> 
;/table> 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



46 



Part I 4 Understanding (X)HTML 



Without comments, the nested tables are hard to follow. However, adding a few 
comments allows you to more easily keep track of the nested elements' purpose: 



</table) 

</table> < 

;/table> <! - 



<. ! - - /Top heading 
-- /Main body --> 
/Floating page - - 



Creating the Basic Structure 



The basic structure for all HTML documents is the same and should include the 
following minimum elements and tags: 

4 <D0CTYPE> — The declared type of the document 

4 < h t m 1 > — The main container for HTML pages 

4 < h e a d > — The container for page header information 

4 < t i 1 1 e >— The title of the page 

4 <body> — The main body of the page 

These elements fit together in the following template format: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.ong/TR/html4/strict.dtd"> 
<html> 
<head> 

<meta . . . meta tags go here ... > 

<ti tl e> ti t le of the page/ document goes here</ti tl e> 

< L I N K nel ="styl esheet" \\ref=" externa 1 style sheet name" 

type="text/css"> 
<style> 

... any document specific styles go here ... 
</style> 

< s c n i p t > 

... client-side scripts go here ... 

</scnipt> 
</head> 
<body> 

. . . body of document goes here, paragraphs modified by 
block elements, characters , words and sentences modified by 
in 1 i ne el ements . . . 
</body> 
</html> 

The following sections provide more detail on each of the various elements. 



Declaring the Document Type 



The <D0CTY PE> declaration defines what format your page is in and what 
standard(s) it follows. This is done by specifying what DTD the document adheres 



PI: JYS 
WY022-03 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



Chapter 3 ♦ Starting Your Web Page 



to. For example, the following <D0CTYPE> definition specifies the strict HTML 4.01 
DTD: 



1D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 01// Eh 

"http://www.w3.org/TR/htnil4/strict.dtd"> 




t Cross- 
Reference 



The format and options of the <D0CTYPE> tag are covered in more detail in 
Chapter 2. You can find a list of valid, public DTDs on the W3C Web site at: 

http://www.w3.org/QA/2002/04/val id-dtd-list.html. 



This book will cover the strict HTML 4.01 DTD unless otherwise noted. 



Specifying the Document Title 



The <head> element of an HTML document contains several other elements 
including the document title. The document title is delimited between <t i 1 1 e> tags 
and can include any character or entity. For example, consider the following <head> 
section that includes a copyright symbol: 

<title>This Page Copyright  2003</title> 
This title shows in the title bar of Internet Explorer, as shown in Figure 3-1. 



,: >Th 



Copyright symbol 
I 



is Page Copyright © 2003 - Moiilla Firebird 



aia 



File Edit View Go Bookmarks Tools Help 



N 



"3>'~*& j fj) Q http://localriost/title-sample.ritml gg Q, 



Figure 3-1: Entities are rendered correctly in document titles. 



Although it is useful to have the title of your document in the title bar of the client's 
browser, the title is used in several other locations, as well — it is used as the default 
shortcut/favorite name in most browsers, it is linked to in most search engines, and 
so on. As such, you should always include a title for your documents, and make it as 
descriptive (but concise) as possible. 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



Part I ♦ Understanding (X)HTML 



Providing Information to Search Engines 

The <head> section of your document can also include <meta> tags. These tags are 
not rendered as visible text in the document — they are used to pass information and 
commands to the client browser. 

As its name implies, the <meta> tag contains meta information for the document. 
Meta information is information about the document itself, instead of information 
about the document's contents. Most of a document's meta information is generated 
by the Web server that delivers the document. However, by using <meta > tags, you 
can supply different or additional information about the document. 

The amount of information you can specify with <meta > tags is quite extensive. If 
you use the HTTP-EQUIV parameter in the <meta> tag, you can supply or replace 
HTTP header information. For example, the following <meta > tag defines the content 
type of the document as HTML with the Latin character set (ISO-8859-1): 

<meta http -equi v="Content -Type" content="text/html ; charset=I SO-8859- 1"> 

In addition, you can control some aspects of how the client browser treats the 
document. You can specify how long the document should be cached (if cached at 
all), refresh the browser with a different page after a delay and so forth. For example, 
the following two <meta > tags tell the browser not to cache the current page 
(pragma, no- cache) and to refresh the browser window with a different page after 3 
seconds (refresh): 

<meta http-equi v="pragma" content="no-cache"> 

<meta http -equi v="refresh" 

content="3;URL=http: //www. example.com/newpage. html "> 

Note For a comprehensive list of HTTP 1.1 headers, seethe HTTP 1.1 definition on the 

W3C Web site: http: //www. w3.org/Protocols/rfc2616/ rfc2616.html. 

Always include at least a minimum amount of information in your documents to aid 
search engines in correctly categorizing your documents. Two important pieces of 
meta information are a description of the document and keywords relating to its 
content. The description and keywords information is provided by the following two 
<meta> tags: 

<meta name="descri pti on" content="The latest movie news") 
<meta name="keywords" content="movi e , movies, production, 

genre, sci fi , horror, drama, comedy, anima, manga, news, 

chat, bbs, discuss, review, recent") 



Search engines such as Google (www . googl e . com) will also list the provided 
description and keywords in the site's entry. 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



Chapter 3 ♦ Starting Your Web Page 



Setting the Default Path 



When defining links and references in your HTML document, be as exact as possible 
with your references. For example, when referencing a graphic with an < I MG> tag, 
you should make a habit of including the protocol and the full path to the graphic, as 
shown in the following line of code: 

<img src="http: //www. example. com/ images/sa ilboat.gif") 

However, it isn't very practical to type the full path to every local element that is 
referenced in your document. As such, a document residing on the exampl e . com 
server could reference the same graphic with the following code: 

<img src=" images/sa ilboat.gif") 

But, what happens if the document is relocated? The images directory might no 
longer be a subdirectory of the directory where the document resides. The image 
might be on a separate server altogether. 

To solve these problems, you could use the < b a s e > tag. The < b a s e > tag sets the 
default document base — that is, the default location for the document. Using the 
preceding example, a document in the root directory of the exampl e . com server 
would have a <ba s e> tag similar to the following: 

<base href="http: //www. example. com/document. html "> 

Any absolute references in the document (those with full protocol and path) will 
continue to point to their absolute targets. However, any relative reference (those 
without full protocol and path) will be referenced against the path in the < b a s e > tag. 



Creating Automatic Refreshes and Redirects 

Meta tags can also be used to refresh a document's content or redirect a client browser 
to another page. Refreshing a document is useful if it includes timely, dynamic data, 
such as stock prices. Redirection comes in handy when a document moves — you 
can use a redirect to automatically redirect a visitor to the new document. 

To refresh or redirect a document, use the http-equiv "refresh" option in a <meta > 
tag. This option has the following form: 

<meta http-equi v="ref resh" content=" seconds_to_wa i t ; ur]"> 

For example, suppose that a page on your site (exampl e . com) has moved. The page 
used to be on the root of the server as bi o . html , but now the page is in a bi o 
directory as index.html (/bio/index.html). However, you want visitors who 
previously bookmarked the old page to be able to get to the new page. Placing the 
following document in the server's root (as bio. html) would cause visitors to 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



50 Part ' ♦ Understanding (X)HTML 



automatically be redirected to the new page after a three-second wait: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

■•http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>My Bio has Moved ! </ti tl e> 

<meta http-equi v="pragma" content="no -cache") 

<meta http-equi v="refresh" content="$3$ ; 

URL= http : / / www. examp 1 e. com/ bi of i ndex. html"> 
</head> 
<body> 

<p>My bio has moved. You will be redirected to the new page 
in 3 seconds, or you can click the link below. </p> 
<a href="http : //www. exampl e . com/bi o/i ndex . html ">My new 
bio.</a> 
</body> 
</html> 

To refresh the current page, simply place its absolute URL in the refresh tag. 

T 'P Using the pragma no -cache meta tag along with the refresh tag is always 



/ 



a good idea. This helps keep the browser from caching the document and 
displaying the cached copy of the document instead of the updated document. 
Because different browsers treat the no cache pragma differently, it is also a 
good idea to add an expi res meta tag, as shown below: 

<meta http-equi v="expi res" content="0"> 

This tag causes the document to be immediately expired in the cache and, 
hence, not cached at all. 



Page Background Color and 
Background Images 



One of the easiest changes you can affect on your Web pages is to change the 
background color of your document. Most browsers use a white background, and 
specifying a different background color or a background image can easily make your 
document distinct. 



Specifying the document background color 

If you code your HTML against the transitional format of HTML, you can use the 
bgcol or attribute in the <body> tag. However, using that attribute is not 
recommended for the following reasons: 

♦ The attribute is not valid for strict HTML and might impair the validation of 
your document. 

♦ If you want to change the background color of your documents, you must 
change each individual body tag in each document. 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



Chapter 3 ♦ Starting Your Web Page 



A better practice is to use appropriate styles, typically in an external style sheet. 

The document background color is set using the background -col or property. For 
example, to set the background color to blue, you would use the following style 
definition: 



(style) 

body { background -col or : blue; 
;/style> 



Reference For more information on styles, refer to Chapters 15 and 16. 



Specifying the document background image 

Besides setting the background of the document to a solid color, you can also specify 
an image to use as the document background. As with the background color 
attribute for the body tag, there is also a background image attribute (background) 
for the body tag. However, as with the background color attribute, it is not a good 
idea to use that attribute. 

Instead, use the background-image property in the body style, as shown here: 



ifrMfirillaFirehird 


BOB 


File Edil View Go Bookmaifcs Tools Help 


W 


® " -# -^ i te [Q l«lp:JWMalhosl*ackgiouiid-saiii|ile.h1r v] C^| 




Done 

Figure 3-2: The grid in the background of the document is courtesy of an 
image, grid . jpg. 



PI: JYS 

WY022-03 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 7, 2004 21:15 



52 Part I ♦ Understanding (X)HTML 



<style> 

body { background - image : url ( path_to_iniage) ; I 
</style> 

For example, the following style results in g r i d . j p g being placed as the document's 
background: 

<style> 

body { background - image : url ( gri d . jpg ) ; ) 
</style> 



Note 



The effect is shown in Figure 3-2. 

When you change the background color to a dark color, or use a dark image, 
you should also change the text color so it will contrast with the background. 
For example, the following style sets the body background to black and the 
body text color to white: 



:style> 

body { background -col or : black; color: white; I 
:/style> 



Summary 



This chapter described the basic elements you need in all HTML documents. You 
learned some basic guidelines for coding with HTML and how to add header 
information to your documents, such as a title and meta information for search 
engines. You also learned how to set a document's base path and redirect a user to 
another page. Lastly, you saw how to quickly make a document distinctive by 
changing its colors. 

The next few chapters cover various formatting elements in more detail. 

♦ ♦ ♦ 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



HTML/XHTML 

Authoring 

Fundamentals 



In This Part 

Chapter 4 

Lines, Line 
Breaks, and 
Paragraphs 

Chapter 5 

Lists 

Chapter 6 

Images 

Chapter 7 

Links 

Chapter 8 

Text 

Chapter 9 

Special 
Characters 

Chapter 10 

Tables 

Chapter 1 1 

Page Layout with 
Tables 

Chapter 12 

Frames 

Chapter 13 

Forms 

Chapter 14 

Multimedia 

Chapter 15 

Scripts 



53 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 




54 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Lines, Line 
Breaks, and 
Paragraphs 



Just as the Web is made up of individual pieces — documents 
or pages — those individual pieces are made up of smaller 
elements themselves. Just like a textual document created 
with a word processor, HTML documents comprise 
paragraphs and other block elements. This chapter examines 
block elements in detail. 



Line Breaks 

As mentioned in previous chapters, HTML is very forgiving of 
white space — perhaps a bit too forgiving. Instead of simply 
reproducing the white space contained within the code, client 
browsers follow the rules of HTML, condensing white space 
and only inserting formatting via tags. 

For example, consider this code example: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<ti t 1 e>Excerpt From Haml et</t i tl e> 
</head> 
<body> 
Scene I. Elsinore. A platform before the Castle. 

[Francisco at his post. Enter to him Bernardo.] 

Ber . 

Who's there? 

Fran . 

Nay, answer me: stand, and unfold yourself. 



IIS 

Line Breaks 
Nonbreaking Spaces 
Soft Hyphens 
Preserving Formatting 
Indents 
Headings 
Horizontal Rules 
Grouping with <di V> 
♦ ♦ ♦ ♦ 




55 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



56 PartM ♦ HTML/XHTML Authoring Fundamentals 



Ber . 

Long live the king! 

Fnan . 
Bernardo? 

Ber . 
He. 

Fran . 

You come most carefully upon your hour. 

Ber . 

' Ti s now struck twelve. Get thee to bed, Francisco. 

Fran . 

For this relief much thanks: 'tis bitter cold, 

And I am sick at heart. 

Ber . 

Have you had quiet guard? 

Fran . 

Not a mouse stirring. 

</body> 

</html> 

This text, when rendered by a browser, resembles that shown in Figure 4-1. Note how 
the formatting has been completely changed due to the browser condensing all the 
white space — only rendering one space where line breaks and multiple spaces appear. 

This has advantages and disadvantages, linked to the following two points: 

♦ You can format your code almost however you like without worrying about 
affecting the formatting in the client browser. 

♦ You cannot rely upon visual formatting — using multiple spaces, tabs, and line 
breaks — to format your HTML documents. 

Instead of using plain text, you must use HTML tags to break your document into 
discrete paragraphs. 



Paragraphs 



In HTML, paragraphs are delimited by the paragraph tag, <p>. The paragraph tag 
controls the line spacing of the lines within the paragraph as well as the line spacing 
between paragraphs. The default spacing is single space within the paragraph, and 
double-space between paragraphs. 

Each paragraph in your document should start with an opening paragraph tag (<p>) 
and end with a closing paragraph tag (</p>). This ensures that each paragraph in 
the document has the same formatting. For an example of using paragraph tags, 
consider the following code and its output, shown in Figure 4-2: 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



*-l] E.N<_ti|.H Fn. in hi- ii i il -H- ■ - Minji iniihM luieiuel Ex|jlviti 


E®ai 


File Edii View Fiivuiiies Tools Hel|> 


* 


o * j j3zi-&-P**e|&-&s* 


irfrtm^ ^http^/bialhostO^pter^FigM htrn 


FIB- 



Scene I. Elsmorc. A plafcbrm before the Caste. fErsincisco at his post Enter to him Ecmarco.l Ber. n ^ho s there? rran. Kay, 
answer me: s:and, and urifold yourself. Ber. long Jive the king! Prsr.. Bernardo' 7 Ber. He. Brsn. You come most i:a.-efullyupon 
yryi-hcnr "Rp.r 'Tis new ?inin1r tiK. r fi1ir= Get dip. p. to hpd, ^rannisnr: "Fran Trjr t'-rs tr1- Ff rm inb trsrk?' 'tis hitter fold. And T arr 
sick at li;a_"t. Bcr. Have you had qui;: guard? E/an. >~ot amous; sturxg. 



ii': 



- j I rral in 



Figure 4-1: HTML browsers condense white space in the code to single spaces. 



«i '. E^tti|ji Fifiii Bhiuk B^Liuiy - Mfcit-ti-h luivnivi Ex|jluiei 


c®ai 


File Edit View Fiivuiiies Tools Hel|> 


» 


Q - <J a j) ■;!) ^ S# a|ei'Si B4 



Aftrimw ^rttp://b:alhostfCh5ptet4fFigi-2|-tm 



RB 



01 My Early Home 

Thp. first ph ": = that: T n an v/pII r=ti ptnber was a 1 argF r>l p a ? srt meario w with a p on d of nlear watpr r t 5! oine sh a dy t- p. p. s 
leaneo oyer it, andrjs^i;; and water-lilies grew a: the oeep end. Over the hedge on one jjoc wc looked into a plowed Eeld, 
and on the other wj locked ever a .sate at our master's house, whi^i stooc by the roadsicc, at the top ct the meadow was a 
grove of fir trees, anc a: the bottom a running brook overhung; by a. s:eep baric. 

■vY.ile I was young I live d up on my mother 1 1 mlk. as I e oid not e at glass. Ll the daytime I ran by her side, and at night _ lay 
down close by Jisr. When it was hot we used to stand by the pond in the :had2 of the :reec, ar.d when it wtc ::old we had a 
nice warm shed near the grove. 

As soon as [was old enough to cat grass my mother used to go out to work m the os.yhrnc, anc ;smc back mthc evening. 

Therp w=-p siy ^oiing ■i^lts in thp meadow b^iriFS ttf;. the^ wer=: older than ~ was' sorrF ivpre nparlj/ a? srge as .pr^wn-up 
ho/ses. I used to run with them, andbac g/eat fuii; we used to gallop all Together round ano /oundthe field as hard as we 
coid go. Somctm:^ wc had rather rough play, £ov they would frequently bi:c sind kick as well as gallop. 



an: 



Figure 4-2: Paragraph tags control the spacing of lines within and between 
paragraphs in a document. 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



58 PartM ♦ HTML/XHTML Authoring Fundamentals 



pi 

tr 
de 
fie 
ho 
wa 
ov 
<P 

CO 

ni 
st 

CO 

<p 

go 

ev 

<P 
we 
ho 
to 
we 
wo 
</ 
</ 



DOCT 
"ht 
tml> 
ead> 
<tit 
head 
ody> 
>01 
>The 
easa 
ees 
ep e 
Id, 
use , 
s a 
erhu 
>Whi 
uld 
ght 
and 
1 d w 
>As 

out 
eni n 
>The 
re o 
rses 
gal 
cou 
uld 
body 
html 



YPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 
tp : //www. w3.org/TR/html4/strict.dtd"> 



le>Excerpt From Black Beauty</t i tl e> 



My Early Home</p> 

first place that I can well remember was a large 
nt meadow with a pond of clear water in it. Some shady 
leaned over it, and rushes and water-lilies grew at the 
nd. Over the hedge on one side we looked into a plowed 
and on the other we looked over a gate at our master's 

which stood by the roadside; at the top of the meadow 
grove of fir trees, and at the bottom a running brook 
ng by a steep bank.</p> 

le I was young I lived upon my mother's milk, as I 
not eat grass. In the daytime I ran by her side, and at 
I lay down close by her. When it was hot we used to 
by the pond in the shade of the trees, and when it was 
e had a nice warm shed near the grove. </p> 
soon as I was old enough to eat grass my mother used to 

to work in the daytime, and come back in the 
g.</p> 

re were six young colts in the meadow besides me; they 
Ider than I was; some were nearly as large as grown-up 
. I used to run with them, and had great fun; we used 
lop all together round and round the field as hard as 
Id go. Sometimes we had rather rough play, for they 
frequently bite and kick as well as gallop. </p> 



Tip It is a good idea to visually format your text within the HTML code— inserting 

line and paragraph breaks where you want them to appear. Doing so facilitates 
formatting the text with tags and identifying where tags are missing. 

As with most tags, you can use styles to control the spacing used by the paragraph 
tag. For example, using the following styles will cause the paragraph's internal line 
spacing to be double-spaced by increasing the line height to double its normal size: 

<style type="text/css"> 

p { line-height: 20035; 1 
</style> 



If this style is applied to the example earlier in this section, it results in the output 
shown in Figure 4-3. 

Cross- For more information on styles, refer to Chapters 16 and 17. 

Reference 




Standard paragraph formatting is left-justified, as shown in Figures 4-2 and 4-3. You 
can control the justification by using a style that modifies the text- al i gn attribute. 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



•ehbb 



Excerpt From Black Beauty - Miciosoft Internet Explorer 



File Edit View Favorites Tools Help 



Q-O-HSftLP** 



:. , h:tp : ;Jloc3lho5tJQiap>er4fFiq4-3 , html 



I' & H 4 



|B« 



01 My Early Home 

The Erst place that I ; an well remember was a Large pleasant meadow with a pond of ;le arwaterir.it. Some shsdy trees 
leaned over it, and rushes and water-lilies grew at the desp end. Over the hedge on one side we looked into a plowed field, 
and :>n the other we oo'^ed over a gate ^t our master's hoii?e, wrmh stood by the -oadside;. at the top of die meadow was a 
grove of fir trees, and at the bottom £ toinning brook overhung by a steep bank. 

^■/liile I was young I lived upon my ii.olhei's milk, as _ uould not eaL glass. In tin: daytime I iaii by l.ci iidc, a:id at iighl I lay 
down close by her. "When it was hot we used to standby the pond in the shade of "lie trees r and when it was cold we had a 
nice warm shed near the grove. 

As seen as I was eld enough to eat grass my mother used to go out to work m die dajtime, and come back in the evening. 

There were six young colts in the meadow besides me; they were older than I was; some were nearly as large as grown-up 
horses, [used to run with them, and had great fun; we used to gallop all together round and round the field as hard as we 
could go. Sometimes wc hs.d rather rough play, for they would frequently bite and kick as well as gallop. 



" 



v 



^)Dore 



*J Local intranet 



Figure 4-3: You can control the spacing within a paragraph by modifying the 1 i ne 
height attribute of the <p> tag. 



For example, to set the standard paragraph justification to center, you would use a 
style similar to the following: 

p 1 text-align: center; ) 



Manual line breaks 

Occasionally, you will want to manually break a line without ending the paragraph. 
For example, consider the example earlier in this chapter from William 
Shakespeare's Hamlet: 



Fnan . 

You come most carefully upon your hour. 

Ber . 

'Tis now struck twelve. Get thee to bed, Francisco. 



Fran . 

For this relief much thanks: 'tis bitter coli 
And I am sick at heart. 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



60 PartM ♦ HTML/XHTML Authoring Fundamentals 



Since the text is from a play, it follows a particular style: 

Actor _name 
Dialogue 

If you use a paragraph tag to cause each line break, you'll end up with output similar 
to the following: 

Fran . 

You come most carefully upon your hour. 

Ber . 

'Tis now struck twelve. Get thee to bed, Francisco. 

Fran . 

For this relief much thanks: 'tis bitter cold, 
And I am sick at heart. 

Instead, you should use a line break tag (< b r >) where you need a line break in a 
paragraph. The preceding text would be coded as follows: 

<p>Fran . <br /> 

You come most carefully upon your hour.</p> 

<p>Ber.<br /> 

'Tis now struck twelve. Get thee to bed, Francisco. </p> 

<p>Fran . <br /> 

For this relief much thanks: 'tis bitter cold, 

And I am sick at heart. </p> 



Note 



Typically, you would use several different styles of paragraph tags to delimit the 
different elements. For example, when formatting a script for a play, you would 
have a class for the actor and another for the dialogue. An example follows: 

<p cl ass="actor">Fran . </p> 

<p cl ass="di al ogue">For this relief much thanks: 

'tis bitter cold,<br /> 

And I am sick at heart. </p> 

That way, you could easily control (and change) the format of each element 
separately. 



Nonbreaking Spaces 



Just as you will want to break some text into discrete chunks, at other times you will 
want to keep text together. For example, you wouldn't want words separated in dates 
(December 25, 2003), awkward phrases that include letters and numbers (24 hours), 
or in some company names ("International Business Machine Corporation"). 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



Suppose you were to use the phrase "12 Angry Men." You would not want a browser 
to split the "12" and "Angry" across two lines, as shown here: 

A good example of this technique appears in the movie "12 Angry Men." 

In cases where you do not want the client browser to break text, you should use a non- 
breaking space entity (&nbsp ;) instead of a normal space. For example, when coding 
the "12 Angry Men" paragraph, you would use something similar to the following code: 

<p>A good example of this technique appears in the movie 
"12AngryMen."</p> 

Cross- A For more information on special characters (entities, and so on), refer to 
Referenced chapter 9. 

The browser will then be forced to keep the phrase together, treating it as one 
cohesive word. 

Tip Nonbreaking spaces have long been used to force formatting on the client 

,v browser. For example, to indent a line by three spaces, HTML coders would use 
* something like the following: 

 Indented by three spaces 

Before robust CSS styles, this was the only way to "space fill" text. However, now 
that there are a myriad of ways to achieve this result using styles, this technique 
becomes sloppy and should not be used. Instead, create an appropriate style 
and use it to achieve the same results. 



Soft Hyphens 



Occasionally, you will want to allow a browser to hyphenate long words to better 
justify a paragraph. For example, consider the following code and its resulting 
output in Figure 4-4: 

<p styl e="text -al i gn : j usti fy ; ">The morbid fear of the number 13, or 

tri ska i dekaphobi a , has plagued some important historic figures like Mark Twain 

and Napol eon . </p> 

In cases where you want a client browser to be able to hyphenate a word if 
necessary, use the soft hyphen entity (&s hy ;) to specify where a word should be 
hyphenated. Using the preceding example, you can hyphenate the word 
"triskaidekaphobia" with soft hyphens: 

<p styl e="text -al i gn : j usti fy ; ">The morbid fear of the number 13, or 

t ri s&shy ; kai &shy ; deka&shy ; pho&shy ; bi a , has plagued some important historic 

figures like Mark Twain and Napol eon . </p> 

The resulting output, shown in Figure 4-5, shows how the option hyphens are used to 
break the word and achieve better justification results. 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



62 PartM ♦ HTML/XHTML Authoring Fundamentals 



Fear of the Number Thirteen - Microsoft Intern... Q[n 



File Edit View Favorites Tools Help 



Address 



|http://localhost/Chapter4/Fig4-4.html 



Go 



The morbid fear of the number 13, or 
tnskaidekaphobia, has plagued some important historic 
figures like Mark Twain and Napoleon. 



Done 



*j Local intranet 



Figure 4-4: Long words can cause problems with fully justified 
text. Note how the first line is spread out to fill the full line width. 



ffi Fear of the Number Thirteen - Microsoft Intern... QSIS 



File Edit View Favorites Tools Help 

a a <a * a* x 

Address 



|http://localhost/Chapter4/Fig4-5.html 



Go 



The morbid fear of the number 13, or triskaidekapho- 
bia, has plagued some important historic figures like 
Mark Twain and Napoleon. 






Done 



*j Local intranet 



Figure 4-5: Optional hyphens are used when the browser needs 
to break a word. 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



Preserving Formatting— The <pre> Element 

Sometimes you will want the client browser to interpret your text literally, including 
the white space and forced formatting (line breaks, and so on). In those cases, you can 
use the preformatted tag (<p re>). The preformatted tag tells the client browser that 
the text within the tag has been preformatted and should appear exactly as it appears 
in the code. The tag also causes all text within to be rendered in a monospace font. 

For example, consider the following output from a MySQL database: 

mysql) select * from settings; 

+ H h 

| name | value 

+ H h 

newsupdate | 1069455632 | 

nel easeupdate | Tue, 1/28, 8:18pm 

status | 

feedupdate | 1069456261 



4 nows in set (0.00 sec) 

If you wanted this to appear in a browser as-is, you would have to use liberal 
nonbreaking spaces and line breaks, as well as specify a monospaced font, as shown 
in the following code: 



<p style 
rnysql >&n 

+ 

|  
&nbsp ; &n 
&nbsp ; &n 

+ 

&nbsp 

&nbsp ; &n 

&nbsp 

&nbsp 

&nbsp 

&nbsp ; &n 

|  

&nbsp ; &n 

+ 

4&nbsp ; r 



="f ont 

bsp ; se 

name&n 

bsp; |& 
bsp ; &n 

newsup 
bsp ; &n 
nel eas 
status 
O&nbsp 
bsp ; &n 
f eedup 
bsp ; &n 



-family: counien;") 

lect*fromsettings;<bn /; 
-- + +<bn /> 



bsp ; &nbsp ; &nbsp 
nbsp ; val ue&nbsp 
bsp ; &nbsp ; &nbsp 

- -H 



&nbsp 
&nbsp 
&nbsp 



&nbsp 
&nbsp 
&nbsp 

+<bn / 



&nbsp ; &nbsp ; 
&nbsp ; &nbsp ; 

<bn /> 



date |  106945 5632 

bsp; |<bn /> 

eupdate&nbsp ; | &nbsp ;Tue , &nbsp ; 1/28 , &nbsp ; 8 : 18pm |<br /) 

8inbsp;8inbsp; 

; 



bsp ; snbsp 

date&nbsp 
bsp ; &nbsp 

- -H 



&nbsp 
&nbsp 
&nbsp 



&nbsp 
&nbsp 
Snbsp 



&nbsp 
&nbsp 
&nbsp 

+<bn / 



&nbsp ; &nbsp ; | <br /; 
1069456261 

<bn /> 



owsinset(0.00sec)</p> 



Not only is this a lot of work, but it also renders the code practically illegible. A 
better way is to simply use the <p re> tag, as follows: 



<pne> 

rnysql) select * fnom settings; 

+ H 

| name | value 

+ H 

newsupdate | 1069455632 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



64 PartM ♦ HTML/XHTML Authoring Fundamentals 



rel easeupdate | Tues, 1/28, 8:18pm 
rolfstatus | 
feedupdate | 1069456261 
+ 1 + 

4 rows in set (0.00 sec) 
</pre> 

As you can see in Figure 4-6, the browser does not attempt to format the text within 
the <p re> tags, and renders it in a monospace font to ensure that the formatting 
appears correct. 



Use of the <pre> Tag - Microsoft Internet Explorer 



~mm 



File 


Eil it 


View Favorites Tools Hel|> 






*' 


o 


o 


a m d p * * © 


9- 


ft S -4 





; . h:tp : )/localho5t/aiapter4IFig4-6 , html 



|B G ° 



mysql> select * from settincs; 



| name 



| value 



I 



| newsupdate | 10694.55632 | 

| releaseurdate | Tue, 1/28, 8: 18pm | 

| status^ | | 

| teeaupciate | lUfc.y4bfc^bl | 

4 rnT.TF; ii =pr. (n.nn =ipn) 



^Dore 



*J Local intranet 



Figure 4-6: The <pre> tag tells the browser that the text has been preformatted and that it 
should be rendered verbatim. 



Preformatted text is best for textual tables, or to set certain element (such as lines of 
code) apart from the main body of a document. 



Indents 



Occasionally, you will want to indent the first line of paragraphs in your documents. 
To do so, you can use the text -indent property of the paragraph tag and an 
applicable style. For example, if you wanted the first line of all paragraphs to be 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



Tip 



indented by half an inch, you would use a style similar to the following: 

<style type="text/css"> 

p { text- indent: . 5 i n ; I 
</style> 

If you want to have different styles of paragraphs in your document— some 
indented, some not indented— define your style using classes. For example, the 
' following code defines an i ndent style of the paragraph tag: 



Cstyle type="text/css"> 

p. indent { text -indent: 
:/style> 



.5 in; } 



You would then specify the class in any paragraph tag where you wanted the 
indent: 

<p cl ass="i ndent">Thi s paragraph will be 
indented. </p> 

An example of indenting the first line of paragraphs is shown in the following code 
and its output in Figure 4-7: 



;idoct 

"ht 
Chtml > 

;head> 
<tit 
<sty 

</st 
;/head 
;body> 
;p>Whe 
or on 
onnec 
f the 
aws o 
espec 
eel ar 
p>We 
reate 
e r t a i 
i b e r t 
i g h t s 
ust p 
ny Fo 
s the 
n s t i t 
r i n c i 
hall 
ruden 
/body 
/html 



YPE HTML PU 
tp : //www. w3 



1 e > F i r s t Li 
le type="te 
p| text-ind 
yle> 



BLIC "-//W3C//DTD HTML 4.01//EN 

.org/TR/htnil4/strict.dtd"> 



ne Indents</title) 

xt/css"> 

e n t : . 5 i n ; 1 



f 
c 
o 
L 
r 
c 
< 
c 
c 

L 

rig 

] 

a 

i 
i 

P 
s 

D 



n in t 
e peop 
ted th 

ea rth 
f Natu 
t to t 
e the 
hold t 
d equa 
n unal 
y and 
, Gove 
owers 
rm of 

Right 
ute ne 
pi es a 
seem m 
c e , in 



he Co 
1 e to 

em wi 
, the 
re an 
he op 
cause 
hese 
1 , th 
i e n a b 
the p 
rnmen 
from 
Gover 
of t 
w Gov 
nd or 
ost 1 
deed . 



urse o 
d i s s o 
th ano 
sepa r 
d of N 
i n i o n s 
s w h i c 
truths 
at the 
le Rig 
u r s u i t 
ts are 
the co 
nment 
he Peo 
ernmen 
g a n i z i 
i k e 1 y 
. .</p> 



f huma 
1 ve th 
ther , 
ate an 
ature ' 

of ma 
h i m p e 

to be 
y are 
hts, t 

of Ha 

i n s t i 
nsent 
become 
pie to 
t, lay 
n g its 
to eff 



n even 
e poli 
and to 
d equa 
s God 
n k i n d 
1 them 

self 
endowe 
hat am 
p p i n e s 
tuted 
of the 
s dest 

alter 
i n g it 

power 
ect th 



t s , it b 
t i c a 1 b a 

assume 
1 s t a t i o 
entitle 
requires 

to the 
evident, 
d by the 
ong thes 
s . - -That 
among Me 

governe 
r u c t i v e 

or to a 
s founda 
s in sue 
e i r Safe 



ecomes 

nds wh 
among 

n to w 
them, 

that 
sepa ra 

that 
i r C r e 
e are 

to se 
n , der 
d, --T 
of the 
b o 1 i s h 
t i o n o 
h form 
ty and 



necessa ry 
i c h have 
the powers 
hi ch the 
a decent 
they should 
t i o n . < / p > 
a 1 1 men are 
a t o r with 
Life, 

cure these 
i v i n g their 
hat whenever 
s e ends, it 

it, and to 
n such 

as to them 

Happiness. 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



66 PartM ♦ HTML/XHTML Authoring Fundamentals 



First Line Indents- Microsoft Internet Explorer 



•ehbb 



File Edit View Favorites Tools Hel|> 



O O ill d « P * t 6|a- 6 i 4 

:. h:tp : j/localhost/Oiapter4f Fig4-7 . html 



When in the Coarse of human events, 1: becomes necessary for one people to dissolve the political bands which have 
connected them with another, and to assume among the powers of the earth : the separate and equal station to which the Laws 
of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the 
causes when impel them to the separation. 

We hold :hese truths to be self-evident, that all men are created equal, that they are endowed by their Crea:or with 
certain unamenable lights, that among these are Life, liberty and the pursuit of Happiness. —That to secure these rights. 
Governments are instituted among Men, deriving their just powers from the consent of the governed, --That whenever any 
Form of Government becomes destructive of these ends : it is the Eight of the People to alter or to abolish it, and to institute 
new Government, laying its foundation on such principles and organizing its powers m such form, as to them shal seem most 
likely to effect their Safety and Happiness. Prudence, indeed... 






*J Local intranet 



Figure 4-7: Using styles, you can control the indentation of paragraphs. 

If you want to indent an entire paragraph, usethepadding-left and, optionally, 
the padding-right attribute. These attributes add additional space to the left and 
right of the block element. For example, to add a half-inch indent to the left of a 
paragraph, you could use this style definition: 

<style type="text/css"> 

p. indent { paddi ng - 1 ef t : 0.5in; ) 
</style> 



Tip 



You can use the <bl ockquote> tag to easily indent a paragraph (both left 
and right). However, this method doesn't allow the type of control possible in 
defining a special style for elements you wish indented. 



Headings 



HTML has six predefined heading tags. Headings use < h > tags containing the number 
of the heading. The <h 1 > tag specifies the highest (most important) level of 
headings, while <h6> specifies the lowest (least important) level of headings. 

As with most textual documents, HTML documents use larger fonts to specify 
higher-level headings. For example, consider the following example and its output, 
shown in Figure 4-8: 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



C ! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 

"http://www.w3.org/TR/htnil4/strict.dtd"> 
Chtml > 
(head) 

<title>Heading Tags</title> 
;/head> 



body> 








hl>Head 


ng 


Level 


K/hl 


h2>Head 


ng 


Level 


2</h2 


h3>Head 


ng 


Level 


3</h3 


h4>Head 


ng 


Level 


4</h4 


h5>Head 


ng 


Level 


5</h5 


h6>Head 


ng 


Level 


6</h6 


p>Norma 


body text.</p 


/body) 








/html) 









H^nliim Ta<js- Microsoft Internet E>:|>l<>iei 






UsM 


File Edit View Favorites Tools Hel|> 






1 


O Q E «i -P iV * © 


9- 


ft S -4 





h:tp : |/localhoit/Criapter4IFig4-8 . html 



|B« 






Heading Level 1 

Heading Level 2 

Heading Level 3 

Heading Level 4 
Heading Lewi 5 

: LnrdE 



Normal body :cKt. 



^Dore 

Figure 4-8: There are six, predefined heading styles in HTML. 



*J Local ir 



Each heading style acts like a paragraph tag, providing an automatic line break and 
extra line spacing after the element. As you can see in Figure 4-8, the default spacing 
after a heading is one line. 

You can use heading tags to delimit a wide range of text. However, their default use is 
to mark headings in a document, much like headings in a textual document. Also, like 
most tags, you can use styles to customize the size and appearance of the heading 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



68 PartM ♦ HTML/XHTML Authoring Fundamentals 



tags. For example, consider the following style code, which defines the first four 
heading levels in relationship to the normal paragraph font: 

<style type="text/css"> 

hi ( font-size: 18pt; font-family: Anial; 

font-weight: bold; ) 
h2 { font-size: 16pt; font-family: Anial; 

font-weight: bold; ) 
h3 { font-size: 14pt; font-family: Anial; 

font-weight: bold; ) 
h4 { font-size: 12pt; font-family: Anial; 

font-weight: bold; ) 
p { font-size: 12pt; font-family: Palatino; 

font -wei ght : nonmal ; ) 
</style> 



Cross- \ Additional font elements and style guidelines can be found in Chapters 8 and 
Reference , ,,_,„ 



Horizontal Rules 



Horizontal rules are used to visually break up sections of a document. The <h r> tag 
creates a line from the current position in the document to the right margin and 
breaks the line accordingly 

For example, if you were reproducing text from a book, you might want to use rules 
to show a break between chapters, as shown in the following excerpt from Anna 
Sewell's Black Beauty: 



< ! DOCTYPE 
"http:/ 

<html> 
<head> 

< t i 1 1 e 
</head> 

<body> 
<p>0ne day 
master was 
was going 
catching D 
as made hi 
saw the ma 
<p>"Bad bo 
not the fir 
There - - t 
my farm ag 
<p>So we n 
looked aft 
we were we 



HTML PUBLIC "-//W3C//DTD HTML 4.01//EK 
/www. w3 .org/TR/html4/strict.dtd"> 



Excerpt of Black Beauty</ti t 1 e> 



he was at this game, and did not know that the 
in the next field; but he was there, watching what 
on; over the hedge he jumped in a snap, and 
ick by the arm, he gave him such a box on the ear 
m roar with the pain and surprise. As soon as we 
sten we trotted up neaner to see what went on.</p> 
y!" he said, "bad boy! to chase the colts. This is 
st time, nor the second, but it shall be the last. 
ake your money and go home; I shall not want you on 
a i n . " < / p > 

even saw Dick any more. Old Daniel, the man who 
er the horses, was just as gentle as our master, so 
11 off.</p> 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs f59 



<hr> 

<p>Chapter 02 The Hunt</p> 

<p>Before I was two years old a circumstance happened 

which I have never forgotten. It was early in the spring; 

there had been a little frost in the night, and a light mist 

still hung over the woods and meadows. I and the other colts 

were feeding at the lower part of the field when we heard, 

quite ... </p> 

</body> 

</html> 

The output of this code is shown in Figure 4-9. 



-Q@m 



Excerpt of Black Beauty - Microsoft Internet Explorer 



File Edit View Favorites Tools Hel|> 



. h:tp : |/localho5t/Chapter4IFig4-9 , html 



P1B G ° 



One day he was at this game, and did not know that the master was in ths next field; but he was there, watching what was 
going on; over the hedge he jumped in a snap, ano catchng Dick by the arm, he gave aim such a box on tae ear as made him 
roar with the pain and surpnse As soon as we saw the master we trolec up nearer to ses what went on. 

"Bad boy! "he said, "bad boy! to chase the colts. This is not the first time ; nor the second, but it shall be the last. Thsre -- ;ake 
your money and go home; I shall not waat you on my farm sgain." 

So we never saw Dick anymore. Old Danish the man who looked afer me horses, was just as gentle as ;>ur master, ss> we 
were well off 



Chapter 02 The Hunt 

Befoie _wasLwoyeais old a cnuuinsLanue happened wluuhl have nevei foigoLLen It was eaily m Ihe spnng. Lheie had been a 
lilllc fiosL m Lhe night, and alight inisL slill hung ova Lhe woods diid meadjwi. I and Ltie oLhe] uolLs we:e f^edmg at Jie lowei 
part of tlie held wher. we heard, quite ... 



^K) Dore * J Local intranet 

Figure 4-9: The <hr> tag inserts a horizontal rule in the document. 



As with most tags, you can customize the look of the <h r> tag by using styles. For 
example, consider the following style: 

<style type="text/css"> 

hr 1 color: red; height: 5px; width: 5035; 1 
</style> 



If this style were added to our last example, the results would be similar to the 
output shown in Figure 4-10. 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



70 PartM ♦ HTML/XHTML Authoring Fundamentals 



File Edit View Favorites Tools Help 


» 


o • o - a is] <& p ti « © 


0' & ■ 4 




Address |^http://bcdho5t/C^F*cr'/Fig1 10. html 


MB* 



One day lie vvtii a. tins game, and did notki.ow that ihe niasLei wtit m the next field, buL lit wis hcic, waLulmig whal wis 
gokg on; ovsr the hedge he jumped in a snap, and catching Dick by the arm. he gave him such a box en the ear as made him 
roar with the pain and surprise. As soon as we saw the master we trotted up nearer to sse what went on. 

"Bad boy!" he said, "bad boy! to chase the colts. This is not the first time, nor the second, but it shall be the last Tnere — take 
you.- monsy and go home; I shall not wan: you on my farm again." 

So we ne^er saw Dick anymore. Old Daniel, the man who looked after the horses, was just as gentle as our master, so we 
were well oF 



~J 



Chapter 02 The Hunt 

Before I was two years ole a ;ircumstance happened waicn I have never forgotten. It was early in tie spring there had oeen a 
iittie frost in the night, and s. iight mist still hung over the woods and meadows. I and the sther ;olts were feeding at ths lower 
part ofthe field when we heard, qur.e ... 



§TJme 



*j Local intranet 



Figure 4-10: You can control various aspects of the horizontal rule, including its width, its 
thickness (height), and the color. 



Grouping with the <div> Element 



Now that you know how to format paragraphs, what about groups of paragraphs? 
Suppose, for example, that you wanted to indent an entire section of text and place a 
border around the section. Although you can accomplish the indent by using styles 
with paragraph tags, the unified border is harder to do. For example, consider the 
following code, which uses styles and paragraph tags: 



< ! DOCTY 

"htt 

(html) 

(head) 

< t i 1 1 

<styl 

p.i 

</sty 
(/head) 

(body) 
(p cl as 
not fee 
lever c 
j i s r e g a 



PE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 
p : //www. w3.org/TR/html4/strict.dtd"> 



e>Paragraph Borders with Paragraph Tags</title) 

e type="text/css"> 

ndent-highlight { padding-left: 50px; 

padding-right: 50px; border: solid 3px; 1 

le> 



s="i ndent - hi ghl i ght")For the first few days I could 
d in peace; but as I found that this terrible creature 
ame into the field, or did me any harm, I began to 
rd it, and very soon I cared as little about the 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



passing of a train as the cows and sheep did.</p> 

<p cl ass="i ndent - hi ghl i ght">Si nee then I have seen many 

honses much alarmed and restive at the sight or sound of a 

steam engine; but thanks to my good master's care, I am as 

fearless at railway stations as in my own stable. </p> 

<p cl ass="i ndent - hi ghl i ght">Now if any one wants to break in 

a young horse well, that is the way.</p> 

</body> 

</html> 

The output of this code is shown in Figure 4-11. Note how each paragraph is 
surrounded by its own border, which is not what you wanted. 



>■ ] P..iitii|iii|>h Bouleis witli P<iKi|Ki|>h This -Miciosoft Internet Exploiei 


,:u 


File Etlit View Favorites Tools Hel|> 


if 


O'O-l 1 0|/> *f« 9-614 



h:tp : |/localhoit/Chapter4IFig4- 1 1 . htral 



|B G ° 






For the first fev/ days I could not feed in peace; but as I found that :his tembb creature neyer came into the 
field, or did me any harm, I began ;o disrega-d it, a-id^ery soon I cared as htle about the passing of a train 
as the cows and sheep did. 



Since then I have seen many horse; much alarmed and restive at the sight or sound of s. steam engine; but 
thanks to my good master's care, I am as fearless at railway stations as in my own s:ab^e. 



Npwif any pne wants to break in a young horse well, that is the way. 



*J Local ir 



(£|Dore 

Figure 4-11: Adding some formatting, such as borders, to paragraph tags causes the 
formatting to distinctly appear around individual paragraphs. 

This is where the division tag (<di v>) comes in handy. The <di v> tag is used to 
delimit divisions of a document, which can include several paragraphs or other 
block elements. 



Instead of defining a style for the paragraph tag, define it as an unattached class (one 
without a specified element) and use it with the <d i v > tag, as in the following code: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



HTML/XHTML Authoring Fundamentals 



ead> 
< t i 1 1 
<styl 



</sty 
head) 

ody> 
i v cl 
>For 
und t 

did 
red a 
eep d 
> S i n c 
stive 

my g 
a t i o n 
>Now 

the 
div> 
body) 
html) 



e > D i vision Borders with Division Tags</title> 

e type="text/css"> 

dent -hi ghl i ght { paddi ng - 1 ef t : 50px; 

padding-right: 50px; border: solid 3px; 1 

le> 



ass = 
the 

hat 
me a 
s li 
id.< 
e th 

at 
ood 
s as 
if a 
way . 



firs 
thi 

ny 

ttl 
/p> 
en 
the 
mas 
i n 
ny 
</p 



dent-high! ight"> 

t few days I could not feed in peace; but as I 

s terrible creature never came into the field, 

harm, I began to disregard it, and very soon I 

e about the passing of a train as the cows and 

I have seen many horses much alarmed and 
sight or sound of a steam engine; but thanks 

ter's care, I am as fearless at railway 
my own stable. </p> 

one wants to break in a young horse well, that 



Note the output of this code in Figure 4-12. 



|^J Division Borders with Division Tags - Microsoft Internet Explorer 
File Edit View Favorites Tools Hel|> 

o-o-i^ l=3 e I p * • e I @ ' a ■ -a 






Address | ^ http : //locdhost/Ciaptcr' /Fig-1 12.html |_*j Q Go 










P or the first few days I c ould not fe e d in p e a; e ; but ai I found that this terrible ere ature 
never came htoths fisld, or did me any harm, I began to disregard it, and very soon I cared 
as fntle about the passing of a Tain as the ;ows and sheep did. 

Since then I have seen many hones much alarmed and rsstve at the sight or sounc of a 
s:earn engine; bat thanks to rnv good master's care, I am as fearless at railway stations as in 
my own s:able. 

Now if any one wants to break in a young horse well, that is the way. 













@Dme *J Local intranet 

Figure 4-12: Moving the border definition to the <di v> tag causes the border to appear 
around the entire division instead of around the individual pieces. 



PI: JYS 
WY022-04 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



Chapter 4 ♦ Lines, Line Breaks, and Paragraphs 



Tip Note that the border in Figure 4-12 appears at the margins of the document, not 

■v at the indent of the paragraphs it surrounds. This is because the style specifies 

' padding-left and paddi ng- ri ght, which affects the spacing between the 

parent element (the border) and its children (the paragraphs). To indent the 

border itself, you would need to specify values for ma rgi n- 1 eft and margi n- 

ri ght. 

Keep in mind that the <di v> tag can be used to group combinations of block 
elements as well — it is not limited to paragraph blocks. For example, you could 
easily have included a headline, horizontal rule, or other block element(s) in the 
paragraphs in the last example, and the border would have been rendered around 
them all. 



Summary 



This chapter covered the details of most of the block elements of XHTML — 
paragraphs, headings, horizontal rules, and more. The next few chapters cover more 
specialized elements, such as lists, images, links, and tables. 



After learning about the various elements you can create in an HTML document, Part 
II of this book shows you how Cascading Style Sheets (CSS) contribute to creating 
rich, online content. 



PI: JYS 

WY022-04 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 15:27 



74 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Lists 



HTML and its various derivatives were originally meant to 
be able to reproduce academic and research text. As a 
consequence, particular care was taken to ensure specific 
elements — such as lists and tables — were implemented and 
robust enough to handle the tasks for which they serve. 

In the case of lists, HTML defines three different types of lists: 
ordered (commonly known as numbered) lists, unordered 
(commonly known as bulleted) lists, and definition lists (for 
term and definition pairs). This chapter covers all three types 
of lists and the various syntax and formatting possibilities of 
each. 



Understanding Lists 



Note 



All lists, whether ordered, unordered, or definition, share 
similar elements. Each HTML list has the following structure: 

<1 i st_tag> 

<i tem_tag>I tern text</i tem_tag> 
<i tem_tag>I tern text</i tem_tag> 

</l i st_tag> 

Definition lists are slightly different in syntax because 
they have an item tag (<dt> or "definition term") and a 
definition description tag (<dd >). See the Definition Lists 
section later in this chapter for more information. 

For each list you need the list opening tag, a corresponding 
closing tag, and individual item tags (paired; open and close). 

Each type of list has its own display format: 

♦ An ordered list precedes its items with a number or letter. 

♦ An unordered list precedes its items with a bullet (as in this 
list). 

4- A definition list has two pieces for each item, a term and a 
definition. 




♦ ♦ ♦ ♦ 
In This Chapter 

Understanding Lists 
Ordered (Numbered) Lists 
Unordered (Bulleted) Lists 
Definition Lists 
Nested Lists 

♦ ♦ ♦ ♦ 




75 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Part II ♦ HTML/XHTML Authoring Fundamentals 

The ordered and unordered lists have many different display options available: 

♦ Ordered lists can have their items preceded by the following: 

• Arabic numbers 

• Roman numerals (upper- or lowercase) 

• Letters (upper- or lowercase) 

• Numerous other language-specific numbers/letters 

♦ Unordered lists can have their items preceded by the following: 

• Several styles of bullets (filled circle, open circle, square, and so on) 

• Images 

More information on the individual list types is provided in the following sections. 



Ordered (Numbered) Lists 

Ordered lists have elements that are preceded by numbers or letters and are meant 
to provide a sequence of ordered steps for an activity. For example, this book uses 
numbered lists when stepping the reader through a process. Such a list might 
resemble the following: 

1. In Internet Explorer, open the Web page that displays the graphic you wish to 
use as wallpaper for your desktop. 

2. Right-click the image to open the context menu. 

3. Choose Set as Background to save the image and use it as your desktop 
wallpaper. 

Ordered lists use the ordered list tag (<ol >) to delimit the entire list and the list item 
tag (<1 i >) to delimit each individual list item. 

In the preceding example, the list has three elements numbered with Arabic 
numbers. This is the default for ordered lists in HTML, as shown in the following 
code, whose output is shown in Figure 5-1: 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EK 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<ti tl e>Exampl e Ordered List</title> 
</head> 
<body> 
<ol> 



PI: JYS 

WY022-05 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ 



<li>In Internet Explorer, open the Web page that displays 

the graphic you wish to use as wallpaper for your 

desktop. </l i > 

<1 i >Ri ght -cl i ck on the image to open the context menu.</li: 
<li>Choose Set as Background to save the image and use it 

as your desktop wal 1 paper . </l i > 

</ol> 

</body> 

</html> 



^jfx^mpk Oidereij Lisi -Microsoft Imtemei: Esploiei 
File Edii Vi«w Ftivfriitas Tools Help 



- m 



■J 



i«] i5i ^ p *• e 0t& s.4 



Ad*«s 1^1 hltp:;^)i:*DstMh^itef5^ig5-l.t*ml 



, 



I 



| Go 



1 . Ed Internet Explorer, open the "Web p age that displays the graphic you 
wish bo use as wallpaper Ebr your desktop. 

2. Right-click on the image to open the context menu 

3. Choose Set as Background to save the image and use it as your 
desktop wallpaper. 






-el Doras 



*j "Local intranet 



Figure 5-1: The default ordered list uses Arabic numbers for its items. 



To specify a different type of identifier for each item, you would use the list-style 
attribute and define a style for the list, as shown in the following code: 



DOCTYP 
"http 
tml> 
ead> 
<title 
head) 
ody> 
1 styl 
<li>In 
e grap 
sktop . 



E HTML PUBLIC "-//W3C//DTD HTML 4 . 01// Eh 

: //www. w3.org/TR/html4/strict.dtd"> 



Example Ordered List - Letters</title) 



e="l i st-styl e: upper-alpha") 

Internet Explorer, open the Web page that displays 
hie you wish to use as wallpaper for your 
< / 1 i > 



PI: JYS 

WY022-05 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Part II ♦ HTML/XHTML Authoring Fundamentals 



<1 i >Ri ght -cl i ck on the image to open the context menu.</li> 
<li>Choose Set as Background to save the image and use it 

as youn desktop wa 1 1 paper . </l i > 

</ol> 

</body> 

</html> 

This code results in the list items being prefaced with uppercase letters, as shown in 
Figure 5-2. 



| Example Ordered List - Letters - Microsoft Internet Explorer 



- ?m 



File Edit View Favorites Tools Help 






Address 



a @ ft Lp & • e a * s s -a 



| http : //localhost/Chapter5/Fig5-2 , html 



BH 



V 



Go 



A. In Internet Explorer, open the Web page that displays the graphic you 
wish to use as wallpaper for your desktop. 

B. Eight- click on the image to open the context menu. 

C. Choose Set as Background to save the image and use it as your 
desktop wallpaper. 






Done 



*j Local intranet 



Figure 5-2: The upper - al pha value of the 1 ist-styl e attribute causes 
the ordered list elements to be prefaced with uppercase letters. 



Note 



Using letters or Roman numerals only makes sense for organizational lists (out- 
lines, and so on), not for lists that outline a series of steps— especially if the steps 
must be followed in order. 



The 1 i st-styl e- type property supports the following values in CSS2: 



♦ decimal 

♦ decimal-leading-zero 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ List 



Note 



♦ lower-roman 

♦ upper-roman 
4- lower-greek 
4- lower-alpha 
4- lower-latin 

4 upper-alpha 
4- upper-latin 

♦ hebrew 

♦ armenian 
4 georgian 

♦ cjk-ideographic 

♦ hiragana 
4- katakana 

4- hiragana-iroha 
4 katakana-iroha 
4 none 



Some of the 1 i st-styl e- types are font-dependent— that is, they are only 
supported on certain fonts. If you are using a type such as hi ragana with a 
Latin-based font, you will not get the results you intend. 



The list-style- types are self-explanatory. The default type is typically decimal, 
but can be defined by the individual client browser. Keep in mind that your 
document's font and language options must support the language character sets 
used by the 1 i st-type. 

Ordered lists also support the list-style-position property. This property 
controls where the number or character preceding each item appears. The property 
has two possible values: 



4 outside — The number or character appears outside the left margin of the item 
text. 

4 inside — The number or character appears inside the left margin of the item 
text. 



The default is outside, and the difference between the two options is shown in 
Figure 5-3. 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



80 PartM ♦ HTML/XHTML Authoring Fundamentals 



*2j Example Ohleiel List Poshiom - Miciosoft hue met Ex|>loi«i 



"EMH 



File Edit View Favorites Tools Help 



[=1 6 Lp 



* « 



m -a 



Adcrecc Mg[j http://locdhost/tfiaptDr5/Fig5 3.html 



"BH- 



Outside 



Lcrern lpsum dolor sit anet, cor.sectetuer achpiscirg elit, ssd diarn nonumrny nibh euismod tincidunt ut Dorset dolore 
rnagri£ ahquam. erat volutpat. Ut wisi etim £d minim venian, quis nostrud exerci taticn uJlarn;orper suscipitlobortis nisi 
uL ahqjip ix. ea commode uonsequaL. Euis auLeni Viel euniiiiuie d^loi in hendieiiL in vulpuLa,e v^liL east nicies lie 
concequat, vel ilium dolore eu feugitt nulla facilcic at vero eros et accomcan et iusto odio dignicsim qui blar.dit oraecer.t 
luptaturn zzril delenit augue cuis dolore te feugait nulla facilisi. 

Lcrern lpsum dolor sit anet, cor.sectetuer achpiscing elit, ssd diarn nonummy nibh euisrnod tncidunt ut Dorset dolore 
rnagns ahquam. erat volutpat. Ut wisi enni £d nunini venian, quis nostrud exerci taticn ullam;orper suscipitlobortis nisi 
ut aliquip 5X ea cornrnods consequat. Euis autern vel eurniriure dolor in hendrerit in vulputa:e vslit esse rnclestie 
consequat, vel ilium dolore eu feugkt nulla facilisis at vero eros et accarnsan et iusto odio dignissim qui blar.dit oraeser.t 
lupLaLum zziil delemL iiugue cuis doloie le ftugail. nulla facilisi. 



Inside 



1. Lorernipsurn dolor sit amet, consectetuer adipiscing elit, sed diam nonumrny nibh euismod tincidunt ut koreet dolore 
magns ahquam erat volutpat. Ut wisi enni £d nunirn venian, quis nostrud exerci taticn ullam;orper suscipitlobortis nisi 
ut ahqjip sx ea commode consequat. Euis autem vel eurniriure dolor in hendrerit in vulputa:e vsht esse rnclestie 
cousequal, vel ilium dolor, e eu feugitd nulla facilsis aLvcioeios el. ace Jinsaii el. iusLo odio dogma smi qui blai.diL oiaesei.L 
luptaturn zznl delenit augae cuis dolore te feugait nulla facilisi. 

2. Lorernipsurn dolor sit amet consectetuer adipisciri£ eht r sed diam noiuimrny nibh euismod tincidunt ut koreet dolore 
magns ahquam erat volutpat. Ut wisi etini £d nunini venian, quis nostrud exerci taticn ullam;orper suscipitlobortis nisi 
ut ahqjip sx ea commodo consequat. Euis autem vel eurniriure dolor in hendrerit in vulputa:e vsht esse rnclestie 
consequat, vel ilium dolore eu feugist nulla facilsis at vero eros et accarnsan et iusto odio dignissim qui blar.dit oraeser.t 

* j Local intranet 






- 



Figure 5-3: The list-style-position property controls where the list item numbers/characters 
appear— outside or inside the list item margins. 



Changing the Start Value of Ordered Lists 



Previous versions of HTML allowed the use of the start attribute in the <ol > tag to control 
what number or letter the list began with. For example, the following code starts a list with 
the decimal number 12: 

<ol start="12" styl e="l i st-styl e : decimal;") 



However, the start attribute of the <ol > tag was deprecated, and a replacement CSS style 
has yet to be defined. Although you can use the start attribute, your document will no 
longer validate against strict HTML. 

If you find yourself needing consistent, yet flexible numbering, consider using the new CSS2 
automatic counters and numbering feature. This feature uses the content property along with 
the new counter-increment and counter-reset properties to provide a flexible yet powerful 
automatic counter function. 



The following style code will define a counter and cause any <ol 
number of 12: 



list to begin with an item 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ 



<style type="text/css"> 
ol { counter-reset: list 11; ) 
li { list-style-type: none; I 
1 i : b e f o r e { 

content: counter(list, decimal) " . "; 

counter- i ncrement : list; 1 
</style> 

This code introduces quite a few CSS2 concepts— pseudo-elements, counters, and related 
properties and methods. However, it isn't as complex as it might first appear: 

♦ The ol definition causes the counter (list) to be reset to 1 1 every time the <ol > tag is 
used— that is, at the beginning of every ordered list. 

♦ The 1 i definition sets the list style type to none— the counter will display our number; if 
we left the list style type set to decimal, there would be an additional number with each 
item. 

♦ The 1 i : before definition does two things: 1) causes the counter to be displayed 
before the item (using the begi n pseudo-element and the content property) along 
with a period and a space; 2) increments the counter. Note that the counter increment 
happens first, before the display. That is the reason you need to reset the counter to one 
lower than your desired start. 

Using the preceding styles along with the following list code in a document results in a list 
with items numbered 12-15: 



(ol> 

<ii: 
<ii: 
<ii: 
<ii: 

</ol> 



Item 12</li: 

Item 12</li: 

Item 12</li: 

Item 12</li: 



Counters are a new, powerful feature of CSS2. Unfortunately, at the time of this writing, only 
the Opera browser fully supports counters. However, the other browsers are sure to follow 
suit. You'll find more information on counters and the content property in Chapter 16. 



Tip The various list properties can all be defined within one property, 1 i st-styl e. 

The 1 i s t - s ty 1 e property has the following syntax: 



> 



list-style: <1 i st -styl e -type) 
<list-style-position> 



Hist -styl e - image) 



You can use this one property to specify one, two, or all three 1 i s t - s ty 1 e prop- 
erties in one declaration. For example, to define an ordered list with lowercase 
letters and inside positioning, you could use the following tag: 

<ol styl e="l i st -styl e : lower-alpha inside;") 

See Chapters 16 and 17 for more information on styles. 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



82 PartM ♦ HTML/XHTML Authoring Fundamentals 



Unordered (Bulleted) Lists 

Unordered lists are similar to numbered lists except that they use bullets instead of 
numbers or letters before each list item. Bulleted lists are generally used when 
providing a list of nonsequential items. For example, consider the following list of ice 
cream flavors: 

♦ Vanilla 

♦ Chocolate 

♦ Strawberry 

Unordered lists use the unordered list tag (<ul >) to delimit the entire list and the list 
item tag (<1 i >) to delimit each individual list item. 

In the preceding example, the list has three elements each preceded with a small, 
round, filled bullet. This is the default for unordered lists in HTML, as shown in the 
following code, whose output is shown in Figure 5-4: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 



© Example Unordered List - Microsoft Internet Explorer 



0(3© 



File Edit View Favorites Tools Help 



Address &] http://localhost/Chapter5/Fig5-4,html 



a 



",) 



Go 



Vanilla 

Chocolate 

Strawberry 



±1 



Done 






*J Local intranet 



Figure 5-4: An example of an unordered list. 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ 



<title>Example Unordered List</title> 
</head> 
<body> 
<ul> 

< 1 i > V a n 1 1 1 a < / 1 i > 

<li>Chocolate</l i> 

<1 i >Strawberry</l i > 
</ul> 
</body> 
</html> 

Unordered lists also support the 1 i st- styl e- type property, but with slightly 
different values: 

4- disc 

♦ circle 
4- square 

♦ none 

The default bullet type is disc, though the client browser can define the default 
differently. The different bullet types are shown in Figure 5-5. 



uisim 



Example Urioi<leie<l List Bullet Types - Microsoft Internet Exr.'loiei 



File Edit View Favorites Tools Hsl|> 

am .£ p * * e | a • & s ■» 



Address -b ■_■ hztp^/localhost/ChapterB'FigS-B.html 



ft 
B 



disc 






• VanJla 

• Chocolate 

• Strawberry 



circle 



o VanJla 
o Chocolate 
o Strawberry 



square 



■ Vardla 

■ Chocolate 

■ Strawberry 



VanJla 

Chocolate 

Slitivvbcii^ 



-i 



"■y Local intranet 



]Dore 



Figure 5-5: An example of the different bullet types for unordered lists. 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



84 PartM ♦ HTML/XHTML Authoring Fundamentals 



As with ordered lists, you can define the list-style-position property, which in 
the case of unordered lists controls where the bullet appears — outside or inside the 
left margin of the item. For example, to move the bullet inside the item margins you 
would use a style with the < u 1 > tag similar to the following: 

<ul styl e="l i st -styl e-posi ti on : inside;") 

Unordered lists support one other type of bullet for each item, an image. The image 
for use in unordered lists must fit the following criteria: 

♦ Be accessible to the document via HTTP (be on the same Web server or 
deliverable from another Web server) 

♦ Be in a suitable format for the Web (jpg, gif, or png) 

♦ Be sized appropriately for use as a bullet 

To specify an image for the list, you use the 1 i st-styl e- i mage property. This 
property has the following syntax: 

list-style- image: url ( url_to_image) ; 

This property can be used to add more dimension to standard bullets (for example, 
creating spheres to use instead of circles) or to use specialty bullets that match your 
content. For example, consider the two graphics shown in Figure 5-6, created in 
Jasc's Paint Shop Pro. 



- , J.toc Paint Shop Pro - Imagc2 



"sua 



File EhMt tfiaw Image Effects Colore Layani Objects Sanctions Masks Whitlow Htl|> 



a isu, 



2 A % e. | IS :z. m m H DH Zi K? li 




Figure 5-6: Two graphics that can be used as bullets. 



PI: JYS 

WY022-05 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ 



Of course, the graphics must be scaled down to "bullet" size and saved in a 
Web-friendly format. In this case, the graphics are reduced to 10-20 pixels square and 
saved on the root of the Web server as sphere, jpg and cone . j pg. The following 
code uses the images, and the output is shown in Figure 5-7. 

< 1 D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/htnil4/strict.dtd"> 
<html> 
<head> 

<ti tl e>Exampl e Unordered List with Image Bui 1 ets</t i tl e> 
</head> 
<body> 

<p><b>sphere</b></p> 
<ul styl e="l i st-styl e -image : url ( sphere . jpg ); "> 

<li>Vanilla</li> 

<li>Chocolate</l i> 

<1 i >Strawberry</l i > 
</ul> 

<p><b>cone</b></p> 
<ul styl e="l i st-styl e -image : url ( cone . jpg ); "> 

<li>Vanilla</li> 

<li>Chocolate</l i> 

<1 i >Strawberry</l i > 
</ul> 
</body> 
</html> 



© Ex.ini|>le Unordered List with Image Bullets - Miciosof... 3(s]u 
File Edit View Favorites Tools Help j? 



O T O0i3fS PiV«r© 0i 



Address 



|http://localhost/Chapter5/Fig5-7,html 



Go 



sphere 



©Vanilla 
9 Chocolate 
m Strawberry 



^Vanilla 



m 



Chocolate 



-= Strawberry 



v| 



Done 



y Local intranet 



Figure 5-7: Using graphics in unordered lists. 



PI: JYS 

WY022-05 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



86 PartM ♦ HTML/XHTML Authoring Fundamentals 



Note A few references state that the closing item tags (</ 1 i >) are not necessary in 

lists. Although most browsers will render the list properly without them, your 
code will not validate against the strict HTML unless you include them. 



Definition Lists 



Definition lists are slightly more complex than the other two types of lists because 
they have two elements for each item, a term and a definition. However, there aren't 
many formatting options for definition lists, so their implementation tends to be 
simpler than that of the other two lists. 

Consider this list of definitions, highlighting popular Web browsers: 

Internet Explorer 

Developed by Microsoft, an integral piece of Windows products. 

Mozilla 

Developed by the Mozilla Project, an open source browser for multiple platforms. 

Netscape 

Developed by Netscape Communications Corporation, one of the first graphical 
browsers. 

Safari 

Developed by Apple Computer, Inc., for Apple's OSX operating system. 

The bulleted items can be coded as list terms and their definitions as list definitions, 
as shown in the following code. The output of this code is shown in Figure 5-8. 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<ti tl e>Exampl e Definition List</title> 
</head> 
<body> 
<dl> 

<dt>Internet Expl orer</dt> 

<dd>Devel oped by Microsoft, an integral piece of Windows 

products . </dd> 
<dt>Mozilla</dt> 
<dd>Devel oped by the Mozilla Project, an open source 

browser for multiple pi atf orms . </dd> 
<dt>Netscape</dt> 
<dd>Devel oped by Netscape Communications Corporation, one 

of the first graphical browsers. </dd> 
<dt>Safari</dt> 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ 



<dd>Devel oped by Apple Computer, Inc, for 
operating system. </dd> 
;/dl> 
;/body> 
;/html> 



jple's OSX 



^] Example Definition List - Microsoft Internet Explorer 



- i@ 



File Edit View Favorites Tools Help 



http : //localhost/Chapter 5/Fig5-8 . html 



ft . ■ 4, 

3H Gd 



Internet Explorer 

Developed by Microsoft, an integral piece of Windows products. 
Mozilla 

Developed by the Mozilla Project, an open source browser for 

multiple platforms. 
Netscape 

Developed by Netscape Communications Corporation, one of 

the first graphical browsers. 
Safari 

Developed by Apple Computer, Inc, for Apple's OSX operating 

system. 






@Done 



\J Local intranet 



Figure 5-8: Definition lists provide term and definition 
pairs for each list item. 



Note 



To add clarity to your definition lists, you will usually want to construct styles 
that set the definition term in a different font or textual style. For example, you 
might want the definition terms to be red, bold, and italic. The following style 
definition accomplishes this: 

<style type="text/css"> 

dt { color: red; font-style: italic; 
font-weight: bold 1 
</style> 



Nested Lists 



You can nest lists of the same or different types. For example, suppose you have a 
bulleted list and need a numbered list beneath one of the items, as shown: 

4- Send us a letter detailing the problem. Be sure to include the following: 

1. Your name 

2. Your order number 

3. Your contact information 

4. A detailed description of the problem 



PI: JYS 

WY022-05 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



88 PartM ♦ HTML/XHTML Authoring Fundamentals 



In such a case, you would nest an ordered list inside an unordered one, as shown in 
the following code: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<ti tl e>Exampl e Definition List</title> 
</head> 
<body> 
<ul styl e="l i st-styl e: disc;"> 

<li>Send us a letter detailing the problem. Be sure to 

include the f ol 1 owi ng : </l i > 
<ol styl e="l i st-styl e: decimal;") <li>Your name.</li> 
<li>Your order number. </li> 
<li>Your contact i nf ormati on . </l i > 
<li>A detailed description of the probl em. </l i > 
</ol> 
</ul> 
</body> 
</html> 

The output of the code is shown in Figure 5-9. 



xample Definition List - Microsoft Internet Explorer 



- S U 



File Edit View Favorites Tools Help 

o - o • a & ■£ p i? m ®\&? & m & 



i' 



Address 



|http://localhost/Chapter5/Fig5-9.htrnl 



T3B' 



Send us a letter detailing the problem. Be sure to include the following: 

1. Your name. 

2. Your order number. 

3. Your contact information. 

4. A detailed description of the problem. 



*j| Local intranet 



Figure 5-9: You can nest different types of lists within one another. 



Note that the nested list does not span any open or close tags — it starts after the 
close tag of the parent's item and before any other tags in the parent list. It is also 



PI: JYS 
WY022-05 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



Chapter 5 ♦ 



formatted (indented) to make it easier to identify in the code. Using this method, you 
can nest any list within any other list. 



Summary 



This chapter covered the ins and outs of the three different list types in HTML: 
numbered, bulleted, and definition. You learned how to define and format each type 
of list and how you can nest lists for more flexibility. 

From here, if you are relatively new to HTML you should progress through the 
chapters in order, learning about the various elements of an HTML document. 
Starting in Chapter 16, you will begin learning how to effectively use CSS to format 
and better control your documents. If you are more experienced with HTML, read 
the chapters that interest you or that you need more information on and then read 
the Chapters in Part III (Controlling Presentation with CSS) to get a good handle on 
using CSS in HTML. 



PI: JYS 

WY022-05 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:41 



90 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Images 



The Web was created as a graphical alternative to 
the text-only limitations of tools such as Gopher. As such, 
images play a pivotal role in Web documents — from being used 
as navigation aids and decoration, to conveying complex 
messages impossible with plain text. This chapter introduces 
the various image formats supported "natively" by most user 
agents and how to incorporate them into Web documents. 



Image Formats for the Web 

Most user agents support, to some degree, three graphics file 
formats: GIF, JPEG, and PNG. The GIF and JPEG formats have 
been supported for quite some time (since the origin of the 
Web), while PNG is relatively new. This section covers the 
basics of the image formats. 



Image compression 



All three of these graphics file formats use some form of 
compression to store your image. Why is compression 
important? Uncompressed images can be large — consider 
Table 6-1, which compares image dimensions, number of 
colors, and file size for some sample, uncompressed images. 

As you can see, with file sizes like this, you would have to limit 
yourself to mighty tiny images, or two-color, such as black and 
white, images. Or, you could compress the files. 



Compression options 



When you implement file compression, you either have to 
throw away some information about the image or find a way to 
store the existing information about the image in a more 
intelligent manner. GIF files throw away some color 
information. JPEG files throw away some information about 
the image itself. PNG files store the information using a more 
intelligent algorithm. 







In This Chapter 

Image Formats for the Web 

Creating Graphics 

Inserting an Image 

Image Alignment 

Specifying Text to Display 
for NonGraphical Browsers 

Size and Scaling 

Image Borders and Maps 

Animated Images 




91 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



92 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 6-1 

Uncompressed Image File Size Comparison by Image 

Dimensions and Number of Colors 



Dimensions 


(in 


Inches) 


Colors 


File Size 


1 x 1 






2 


9K 


1 x 1 






256 


9K 


1 X 1 






16.7 million 


18K 


2x2 






2 


16K 


2x2 






256 


24K 


2x2 






16.7 million 


63K 


3x3 






2 


16K 


3x3 






256 


49K 


3x3 






16.7 million 


139K 



GIF 

GIF was the earliest format in use in inline images on the Web. Version 1 browsers 
could open GIF images inline, but required that JPEG images be opened out-of-line. 
GIF uses a compression scheme — called LZW compression — that predates 
CompuServe, even though you might see it called CompuServe GIF. CompuServe 
implemented LZW compression, thinking it was in the public sphere and then found 
out it was proprietary. A lot of lawyers sorted it out. 

How does GIF work? Simply put, GIF indexes images to an 8-bit palette. The system 
palette is 256 colors. Before you can save your file in GIF format, the utility you are 
using simply makes its best guess at mapping all your colors to one of the 256 colors 
in an 8-bit palette. 

Is a reduction in color depth a problem? That depends. GIF uses dithering to achieve 
colors between two colors on the palette. Even with dithering, however, GIF images 
of a sunset have stripes of color, where a smooth gradation would be more natural. 
GIF images also tend to have more cartoonish colors because flesh tones aren't part 
of the palette. A GIF image of a drawing of something like a checkerboard, however, 
will look just fine. 




Cross- 
Reference 



Note 



See Chapter 38 for a lesson in creating animated GIFs. Transparent GIFs are 
discussed at the end of this chapter. 



A system palette is the 256 colors your monitor is able to display if you set 
your video board only to show 256 colors. These colors differ from a PC to a Mac. 



PI: JYS 

WY022-06 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 93 



JPEG 

JPEG takes a different approach. JPEG stands for the Joint Photographic Experts 
Group, the name of the group that created the standard. With JPEG, you get to keep 
all your colors, but you don't get to keep all the data about the image. What kinds 
of images lend themselves to being compressed with JPEG? A tree. If you take a 
photo of a pine tree, the acorns are in specific places, but when the image is 
compressed and decompressed (opened on your Web page), the computer has to 
approximate where those acorns went, because it had to throw away some of the 
data. Is this a problem? Not with most photos of most pine trees. Faces also take well 
to JPEG because the colors are all there; faces in GIF can look unnatural because of 
the color loss. 

Every generation 3 and higher browser can handle inline JPEGs. JPEGs are also ideal 
for showing gradient filled graphics (when the color changes gradually from one 
color to another). The same graphic would suffer enormously under the GIF 
compression because all those in-between colors wouldn't be there. 

What suffers under JPEG compression? Text, schematic drawings, and any line art. 
Of course, with JPEG, you can select the level of compression (usually either as a 
percentage or as Maximum, High, Medium, or Low). You generally want to use the 
maximum compression level your image can handle without losing image quality. 
You won't know how much compression your image can handle without loss until 
you try it at different levels of compression. 

PNG 

The Portable Network Graphics, or PNG format, was developed exclusively for the 
Web and is in the public domain. The PNG format takes advantage of a clever way of 
storing the information about the image so you don't lose color and you don't lose 
image quality; it is a lossless format. The only drawback is, because the standard is 
so new, only fourth-generation and later browsers support PNG graphics. Eventually, 
PNG will replace GIFs for many color-rich, still image files. Only GIFs can support 
animation and transparency. 

Note File formats that implement compression schemes that discard information 

about the image are called lossy file formats. Both GIF, which discards color 
information, and JPEG, which discards image information, are lossy file for- 
mats. File formats that don't discard any information about an image are called 
lossless. PNG is a lossless compression scheme. 



Image color depth 



In the computer world, everything is black or white, on or off. Computers operate 
in the base two system, so when creating colors, your choices of colors are base 
two numbers. A bit is a representation of on or off (1 or 0). One-bit color uses a 
two-color palette (2 1 ). Two-bit color uses a four-color palette (2 2 ). Eight-bit color 
uses a 256-color palette (2 8 ). Thirty-two-bit color uses a 16.7-million-color palette 
(2 32 )- 



PI: JYS 

WY022-06 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



94 PartM ♦ HTML/XHTML Authoring Fundamentals 



Note Between the two system palettes, there are 216 colors in common. This is 

called the 216-browser-safe palette. By limiting your graphics to colors from 
this palette, you can be sure the browser won't have to guess or dither to 
achieve the color you want. 

You might be thinking: Two colors: that's not so bad. An artist can do a lot with two 
colors; think of the ways you can blend them. Unfortunately, this isn't how computers 
work. When you select a color palette, you get only the colors in that palette, not any 
blends of colors in that palette. 

When you create an image, you want to balance the quality of the image against the 
file size of the image. When you send an image file over the Internet to a Web page, 
you send either information about the palette or you send the actual palette. With 
GIF files, you send a color look-up table (CLUT) with the image. With JPEG files, you 
send a palette. As you can imagine, this makes the files considerably larger. 



Enhancing downloading speed 

What can you do to ensure your pages download quickly? There are a few things: 

4 Limit image file sizes. 

4 Limit the number of images. 

4 Reuse images as much as possible so images can be loaded from cache. 

4 Use frames so only part of the browser windows need to reload. 

4 Use text rather than images, where possible. 

Image file sizes 

You can limit image file sizes by doing the following: 

4 Using the maximum compression your image will take 
4 Using the smallest bit-depth your image can stand 
4 Minimizing the dimensions of your image on the page 

Test your pages at 640 x 480, 800 x 600, and 1024 x 768 to see how they will look to 
different visitors. Often, an image that renders well at 1024 x 768 and doesn't 
dominate the page will look huge and overbearing at 640 x 480. 

Number of images 

How many images is the right number? You might be surprised to learn that 
sometimes very small images with white space between them load faster than one 
large image. 

Take advantage of white space to contribute to your images. You can use two 
intelligent techniques to get more image for the byte. By changing the background 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 95 



color to match the background color of your images, you can keep your images 
smaller. By anti-aliasing the text against that background to blend the edges into the 
background color, you can achieve the look of one large graphic with multiple small, 
fast-loading images. 

Reuse images 

Reusing images is as simple as having a single graphic for "home" on all your pages. 
Have a single bullet graphic (if you can't stand to use the standard bullet) for every 
bullet on every page. Why does this help your pages load faster? Your browser 
checks to see whether an image it needs is already in cache and loads the image 
from cache, if it can. This reduces the number of bytes that actually needs to be 
downloaded. 

Use frames 

How can using frames speed download time? After the initial frameset loads, the 
browser will usually be loading one new frame at a time. Also, because the images 
are probably part of the banner and/or the navigational tools, the frame that does 
reload is less likely to be image-intensive. 



Tip By putting all or most of the images into one of your frames and the mostly 

text-based content into your main frame, you can save visitors from having to 
load the images more than once. After the initial load, subsequent loads will 
be faster. 



/ 



Use text rather than images 

You've read this elsewhere in the book. You can use tricks to make text look 
somewhat like an image. Instead of using a graphic with boxes and buttons for 
navigation, use a table with cells assigned different background colors. 



Creating Graphics 



If you want to create top-notch graphics, the tool of choice among professionals is 
Adobe Photoshop, available for the Mac and the PC (see Figure 6-1). Freeware and 
shareware software programs also are available that perform subsets of the functions 
performed by Photoshop. Photoshop LE, the lite version, ships with many scanners. 



Essential functions 

What should your graphics package be able to do? For existing images, such as 
photographs, you want to sharpen, blur, and perform some special effects on the 
image (for example, posterize, swirl, and mosaic). For images you create on the 
screen, you want to create your own custom palette (so you can send as few colors 
as you need). You also need some basic artist tools, such as a paintbrush, a pencil, a 
spray can, and a magnifying glass for magnifying part of the image to see it better. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



96 PartM ♦ HTML/XHTML Authoring Fundamentals 



beeidhi 



tic Ln 1 Lrraac _3Vcr ii:fc:t h fjci 



HWWIM[i-flnI71 

Over 
/the\Web/ 




^aKihfj 1K= V'/et '.'■'■jf!' for/o .i 



Z:orr _ev=l: " " 




1: "J: il 


Uaxc | 


Over 


r f>i„,i:^„„ 

j TrEnspErEfiCr 1 
| Fr^'JEW Col:r 




"niixnP^MiM m 


Tirfrii riiMii ^ z i 1 1 BelededCol: 


d 



El 



niiiiiiiiiiiinnnrnrnnnnrnnnnrnni 

DE ■ ■■ BE □ HO DE D HD HE DE D HD DE □ HD DE D HD 
ULUJUULUJUHBUJUJBULUJUULBHUULUJU 
BE B HB EB B BB BE D BD HB DE Q HD □■ □ HD DE D HD 
DEDHBBEBBDDBEHBBEDEBBBDEBHBDBBBD 

nrnnnnrnannrnnnnrBBn > 

EJE EJ 313 £2E El ^i£ : ' E3EI ^ 3E3 ZiE EJE El SJE3 EJE El 3Ei EE El ZIE] 

i-jLi lj aEa MEi ej ati &^ ^ aw ; sy mh td iatd *■<& ta >jsj y t; a km 



| K/i | I** 2E*™# ft brcit UlhBUs L-;5>-: Jtwintn 

Figure 6-1: Adobe Photoshop. 



| HHYi<JDr^T^' ,j r5^i 



/'TheVA'ey 



~^V 



3 



-^sr 




Z1E 
7|r 



5? 



t> -to 



■.: v'ii£!:-;;v: 



"1 I • 1 l> II H I Iff I . 



I LM)Tf\ Chanialf H Path- 



"i r 



I; Jci ™Hi>t L.w 



Regardless of whether the image is made by hand or based on a photograph or 
clipart, you need the following capabilities: 



Note 



4- Reduce the bit-depth of any image you want to save as GIF. 

♦ Index the color of the image so you can save the image to GIF. 

4- Save the image as an interlaced GIF. 

4- Save the image as a transparent GIF. 

4 Save the image as a PNG file. 

4 Save the image as a progressive JPEG, which is discussed at the end of this 
chapter. 



Progressive J PECs are a nice addition to a Web page. They work the same as 
interlaced GIFs. Before the entire image has been downloaded, you can begin 
to see the image. Then the images slowly come into focus. 



Free alternatives 

If you aren't ready to commit to a $500 software package to get all these great 
functions, you can work with a number of small, free software packages and services 
that do many of the things previously listed for you. On the Web, you can find sites 
that turn your TIF file into a GIF, or make your GIF an interlaced GIF. The trade-off is 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 



the time. Finding, learning, and using a variety of small packages to solve all your 
imaging needs obviously takes longer than learning one package and using it on your 
desktop. 



Capturing Graphics From Other Sites 



What about taking graphics you like from another site? This is generally not an okay thing 
to do. Unless you have explicit permission from the creator of the images— say, you are 
taking graphics from a site that makes free images available or you have written permission 
from the owner of the site— you are essentially stealing the images from the legitimate owner. 
Images are intellectual property and are protected by copyright laws, and using them without 
permission could get you an invitation to court. 

Just because an image is on a Web page doesn't mean it is in the public domain. Yes, it gets 
downloaded onto your own computer (into cache), and, yes, your browser gives you the 
ability to save the image as a local file (using the right mouse button or prolonged clicking 
on a Mac), but it still doesn't mean you own the image or the right to use the image. If you 
see something you like on another page, write to the page owner and ask if he or she owns 
the image and if you can use it. Chances are, the owner will be flattered by your request. 
Be sure that person owns the image or permission won't mean anything (if the image was 
stolen from somewhere else). 



Note 



Progressive JPEGs and interlaced GIFs 

Once upon a time on the Web, you had to wait for an image to finish loading before 
you knew what it was. Today you can save your files using the progressive JPEG 
format or the interlaced GIF format and watch the image come into focus as it loads. 

The advantage to this approach is a visitor to your site knows roughly what an image 
is before the entire image has downloaded. If download times are long, due to a poor 
Internet connection, for example, the visitor to the site can actually take a link off the 
page before the image has finished loading without missing anything. 

Finally, these two image formats are good because the visitor participates in the 
download time. Instead of waiting for the page to download — sitting idly by — the 
visitor waits for the page to download while watching the images become clearer. 
This is more of a reward for waiting — and less of a sense of waiting — for the visitor. 

Specifying the size of the image in the image tag can also speed up the display 
of your Web pages. See the Size and scaling section later in this chapter for 
more information. 

The sense of "coming into focus" that these types of images provide is the result of 
the way the images are stored. Progressive JPEGs and interlaced GIFs download only 
every eighth line at first, then every fourth line, then every second line, and then, 
finally, the odd-numbered lines. The result is the image goes from blurry to focused. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



98 PartM ♦ HTML/XHTML Authoring Fundamentals 



You create a progressive JPEG or an interlaced GIF by saving it into this format. In 
Paint Shop Pro, when you save a file as a GIF file you can choose whether you want 
the file to be normal or interlaced (see Figure 6-2). Freeware packages are also 
available that convert your regular JPEGs and GIFs into progressive JPEGs and 
interlaced GIFs. 



^ Jasc Paint SliiO|> Pro - cat 






File Edit View Image Effects Colors Layers Objects Selections 


Masks Window Help 




Jj d c*h«| ■: ^ x.% e|e@|[&[=!i[]n heh|k? a 




For Help, press -1 



Image: 482 x 640 x 16 Million - 905 KBytes 



Figure 6-2: Paint Shop Pro allows you to choose whether you want your GIF to be 
interlaced or not. 



Using Transparency 



Two of the Web-supported graphics formats, GIF and PNG, support transparency, the ability 
for parts of images to be completely transparent. Typically, transparency is used to soften 
the edge of images, creating an illusion that the image is not rectangular. For example, see 
Figure 6-3, which shows an image with a standard opaque background and the same figure 
with a transparent background. The image with transparency allows the page background 
to show through. 

Using transparency can open up the design of a document, making it more airy and less 
"blocky." It gives the document a more professional appearance, looking more like a pub- 
lished document than a Web page of the 1980s. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 



Different graphic editing programs handle transparency differently— some assign trans- 
parency to the background layer, some allow you to pick one color that should be trans- 
parent, some programs allow multiple colors to be transparent. Check the Help file for your 
editor to determine how to accomplish transparency. 



Q Transparency - Microsoft Internet Explorer 



seas 







>WWWWWWWWWWWGGWWWWWWWft 



|V| 



VJ Local intranet 



Figure 6-3: Transparency can soften an image, giving the 
appearance that the image is not rectangular. 



Inserting an Image 



Images are inserted into HTML documents using the <i mg> tag. The <i mg> tag, at a 
minimum, takes two attributes, a 1 1 and s re. 

The a 1 1 attribute specifies text that should be displayed in lieu of the image in 
nongraphical browsers (see the section "Specifying text to display for nongraphical 
browsers" later in this chapter). The s re attribute tells the user agent what image file 
should be displayed. For example, if you wanted to include the graphic cat . j pg in 
your document, you could use code similar to the following: 



;img alt="A picture of a cat" src="cat . j p g " 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



100 PartM ♦ HTML/XHTML Authoring Fundamentals 



Note The <img> tag has no closing tag. However, in XHTML the <i mg> tag must be 

closed: 

<img alt="A picture of a cat" src="cat . jpg" /> 

The s rc attribute's value can be a file on the same Web server as the document, or 
any valid URL pointing to an image on a different Web server. Just as with the anchor 
tag, you can use absolute or relative URLs to specify the location of the image to 
display. The reasons for using either URL are the same as the reasons for using 
absolute or relative URLs in anchor tags. 




Cross- 
Reference 



For more information about absolute or relative URLs, see Chapter 7. 



Image Alignment 



Most user agents will attempt to display the image where the <i mg> tag is inserted. 
For example, consider the following HTML code and the resulting display shown in 
Figure 6-4: 



§ Standard Imaye Placement - Microsoft Internet Explorer 



0[n)l^j 



File Edit View Favorites Tools Help 

o-o^a s dip *» «|0-a i-a 



* 



Address 



|http://localhost/Chapter06/Fig0604.html 



BB' 



Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut 
labore et dolore magna aliqua. Ut entrn ad minim veniam, quis nostrud exercitation ullamco 
labons nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehendent in 
voluptate velit esse cillum dolore eu fugiat nulla panatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, 
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, quis nostrud exercitation ullamco labons nisi ut aliquip esea cornmodo 
consequat. Duis aute irure dolor in reprehendent in voluptate velit esse cillum dolore eu fugiat 
nulla panatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt 



mollit anim id est laborum. 




-I 






*J Local intranet 



Figure 6-4: The browser displays the image at the end of the paragraph where the 
<img> tag is located. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 



<p>Lorem 


ipsum dolor 


si t 


tempor incididunt ut 


1 abo 


q u i s n o s t 


rud exercitation 


consequat 


. D u i s a u t e 


i rur 


ci 1 1 urn do 


lore eu fug i at n 


p r o i d e n t , 


sunt in c u 


pa q 


ipsum dol 


or sit amet 


con 


i n c i d i d u n 


t ut labore 


et d 


nostrud exercitation 


ul 1 a 


D u i s a u t e 


irure dolor in 


e u f u g i a t 


nulla pariatur. 


in culpa 


qui of fie i a deser 


a cat" src="cat . jpg"X/p> 



amet, consectetur adi pis icing el it, sed do eiusmod 
re et dolore magna aliqua. Ut enim ad minim veniam, 

ullamco laboris nisi ut aliquip ex ea commodo 
e dolor in reprehenderit in voluptate velit esse 
u 1 1 a pariatur. Excepteur sint occaecat cupidatat non 
ui officia deserunt moll it anim id est laborum. Lorem 
sectetur adipisicing el it, sed do eiusmod tempor 
olore magna aliqua. Ut enim ad minim veniam, quis 
mco laboris nisi ut aliquip ex ea commodo consequat. 
reprehenderit in voluptate velit esse cillum dolore 

Excepteur sint occaecat cupidatat non proident, sunt 
unt mollit anim id est laborum. <img alt="Picture of 



If the user agent cannot fit the image on the current line, it will wrap it to the next 
line and follow the paragraph's alignment and formatting. 

Note how the default formatting (at least for Internet Explorer) of the image is to be 
aligned with the baseline of neighboring text. This isn't always ideal. At times, you 
will want to specify the alignment of the image as it relates to the text and other 
objects around it. Image alignment can be controlled by using the a 1 i gn attribute 
with the <i mg> tag. The align attribute can be set to the values shown in Table 6-2: 





Table 6-2 
Align Attribute Values 


Value 


Function 


Top 


Align with the top of nearby text or object 


Bottom 


Align with the bottom of nearby text or object 


Middle 


Align with the middle of nearby text or object 


Left 


Align to the left of nearby text or object 


Right 


Align to the right of nearby text or object 



Note 



Figure 6-5 shows an example of each of these alignment options. 

Most user agents render items in the order in which they appear in the docu- 
ment. If you are using left-aligned images, they should appear before the text 
that they should be positioned left of. 



However, the align attribute has been deprecated in favor of using styles for image 
alignment. The following CSS properties can be used to help align images: 



♦ text-align — Used in surrounding text, this property aligns the text around an 
image (versus aligning the image itself). See Chapter 8 for more information on 
using the text-align property. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



102 PartM ♦ HTML/XHTML Authoring Fundamentals 



@ Image Alignment Options - Microsoft Internet Explorer S&© 


File Edit View Favorites Tools Help 


eig-Bi «t p * * © i a - & m -a 


Address |@ http://localhost/Chapter06/Fig0605.htrnl | vj Q Go 


Sample test for top alignment. Jmm 




m 

Sample text for bottom alignment. W 




Sample text for middle alignment. JB 




wS ample text for left alignment. 




Sample text for right alignment. 

1 




jjf] Done *J Local intranet 



Figure 6-5: The various alignment options for images. 

♦ float — Floats the image to the right or left of the user agent. Note that some 
user agents do not support the floa t property. The float property allows text 
and other objects to wrap next to the image. 

♦ vertical-align — Aligns the image vertically with neighboring text or objects. 

Note that some user agents need to process the image alignment prior to the text 
around it; if you are using CSS to position your images, it is usually best to position 
the images before neighboring text in your HTML document. 



Specifying Text to Display for 
Nongraphical Browsers 



As mentioned repeatedly in this book, it is important not to get caught up in the 
graphical nature of the Web, forgetting that not all user agents support graphics. In 
addition, some users turn off images in their browser to speed up browsing. You can 
use the a 1 1 attribute of the <i mg> tag to specify text that should be displayed when 
the image cannot. For example, consider the following text and the display in Figure 6-6: 



<p><img alt="Picture of a cat" src="cat . jpg" styl e="float : right" width="70px' 
Lorem ipsum dolor sit amet, consectetur adipisicing el it, sed do eiusmod 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 1 Q3 



tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exencitation ullamco labonis nisi ut aliquip ex ea commodo 
consequat. Duis ante inure dolon in nepnehenderit in voluptate velit esse 
cillum dolone eu fugiat nulla pa ni atur . </p> 



@ Image Alt Attribute - Microsoft Internet Explorer 



File Edit View Fiivorites Tools Help 

O ■ O • S E tt | P *«■© 



Addn 



|http://localhcst/Chapter06/Fic<0606,riSml 



Lorem ipsum dolor sit amet, consectetur adipisicing 

elit, sed do emsmod tempor incididunt ut labore et 

dolore magna aliqua. Ut enim ad minim veniam, quis 

nostrud exercitation ullamco labons nisi ut aliquip ex 

ea commodo consequat. Duis aute lrure dolor in 

reprehendent in voluptate velit esse cillum dolore eu fugiat nulla 

panatur. 




* j Local intranet 



Figure 6-6: The al t attribute specifies text to use when the 
image cannot be displayed. 

Some user agents display the a 1 1 attribute text when the user mouses over 

the image. This allows you to use the a 1 1 attribute to include additional information 

about an image. If you have a lot of information to convey, consider using the 

1 ongdesc (long description) attribute as well. The 1 ongdesc attribute specifies a 

URL to a document that is to be used as the long description for the figure. Note that it 

is up to the user agent to decide how to enable access to the long description, if at all. 



Size and Scaling 



You can specify the size of an image by using the height and width attributes of 
the <i mg> tag. These attributes accept pixel and percentage values, allowing you to 
specify the exact size of an image or a size relative to the current size of the browser 
window. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



104 PartM ♦ HTML/XHTML Authoring Fundamentals 



Tip 



Get in the habit of always using the wi dth and height attributes with your 
<img> tags. These attributes allow the user agent to reserve the correct amount 
of space for the image while it continues to render the rest of the document. 
Without these attributes, the user agent must wait for the image to be loaded 
before continuing to load the rest of the document. 

For example, suppose that you had a large, high-resolution image, but wanted to 
display a smaller version. Using the pixel values of the sizing attributes, you can 
specify a custom size of the larger image. For example, consider the following code 
and the resulting display in Figure 6-7: 

<!-- Full image is 180px wide --> 

< p > F u 1 1 Size Image<img alt="Full size image" 

src="ca r . jpg"X/p> 
<p>Half Size Image<img al t="Hal f -size image" 

src="car.jpg" width="90px"X/p> 



@ Image Sizing - Microsoft Internet Explorer 



: 33 



File Edit View Favorites Tools Help 



Address | @ http : //Iocalhost/Chapter06/Fig0607 , html 



§* IB $ 

~F1H gq 



Full Size Image 



Half Size Image %3 




Z^9_J £^3 



^Done 



Vj Local intranet 



Note 



Figure 6-7: Using percentage values, you can display 
an image at any percentage of its normal size. 

It is important to use both the correct height and width when specifying image 
dimensions in an <img> tag. If you change the proportions of the figure (by 
specifying a wrong width or height), you will end up with a funhouse mirror 
effect— the image will be stretched or shrunk in one dimension. Sometimes this 
can be used for effect, but usually it is accidental. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 1 Q5 



Also note that you can specify only one of the dimensions and have the user 
agent automatically figure out the other. However, the user agent must then 
wait for the entire image to load before progressing with rendering the rest of 
the page, so it is always better to specify both dimensions. 

Image size attributes should not be used as a substitute for an appropriately sized 
graphic. If you need a different sized image, create the appropriate size in an image 
editor and use the new image instead. Although the width and height attributes can 
be used to display an image smaller than it actually is, the user agent must still 
download the entire image — the user agent must then scale the image accordingly. 



Image Borders 



You can use CSS styles to create borders around images. Previous versions of HTML 
supported a border attribute for the <i mg> tag, which worked similarly to the 
border attribute of the <tabl e> tag. However, this attribute has been deprecated 
for use with the <i mg> tag. Instead, you should use styles. 

CSS supports quite a few border properties, as shown in Table 6-3. 



Table 6-3 
CSS Border Properties 



Property 


Options 


Use 


Border 


border-width 


Define a simple border around all four sides 




border-style 


of the object, specifying the width, style, and 




border-color 


color in one property 


border-color 


border-color 


Set the color of the border 


border-style 


border-style 


Set the style of the border 


border-top 


border-width 


Define individual sides of the border 


border-bottom 


border-style 




border-left 


border-color 




border-right 






border-top-color 


border-color 


Define the color of the individual sides of the 


border-bottom-color 




border 


border-left-color 






border-right-color 






border-top-width 


border-width 


Define the width of the individual sides of 


border-bottom-width 




the border 


border-left-width 






border-right-width 






border-width 


border-width 


Define the width of the border 



PI: JYS 

WY022-06 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



106 PartM ♦ HTML/XHTML Authoring Fundamentals 



For example, to define a 4-pixel-wide border around an entire image, you can use the 
following code: 

<img alt="A picture of a cat" src="cat . jpg" 
styl e="border : 4px solid black;"> 

To define a border on just the left and right sides of an image, you would use the 
following: 

<img alt="A picture of a cat" src="cat . jpg" 

styl e="border - 1 eft : 4px solid black; 
border-right: 4px solid black;") 

Tip To simplify defining a different border on one side of an image, use the border 

property first to define a border on all sides and then the appropriate border- 
s 7 de property for the side that is the exception, overriding the previous setting 
for that side. For example, to create a border on all sides of an image except the 
right, you could specify border-top, border- bottom, border- 1 eft, and 
border- right properties individually. Or, you could use just border and 
border- ri ght: 

<img alt="A picture of a cat" src="cat . jpg" 
styl e="border -1 eft : 4px solid black; 
border-right: none;") 



Image Maps 



Image maps provide a way to map certain areas of an image to actions. For example, 
a company Web site might want to provide a map of the United States that allows 
customers to click a state to find a local office or store. 

There are two types of image maps, client-side and server-side. Client-side image 
maps rely upon the user agent to process the image, the area where the user clicks, 
and the expected action. Server-side image maps rely upon the user agent only to tell 
the server where the user clicked; all processing is done by an agent on the Web 
server. 

Between the two methods, client-side image maps are generally preferred. They allow 
the user agent to offer immediate feedback to the user (like being over a clickable 
area) and are supported by most user agents. Server-side agents can also bog down 
a server if the map draws consistent traffic, hides many details necessary to provide 
immediate feedback to the user, and might not be compatible with some user agents. 

Tip If you want an image to be clickable and take the user to one particular desti- 

nation, you don't have to use an image map. Instead, embed the <i mg> tag in 
' an appropriate anchor tag (<a>) similar to the following: 

<a href="catpage . html "Ximg alt="Picture of a 
cat" src="cat . jpg"X/a> 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 1 Q~J 



Specifying an image map 



A client-side image map is generally specified within the contents of a <ma p> tag and 
linked to an appropriate <i mg> tag with the <i mg> tag's usema p attribute. For 
example, to specify a map for an image, travel . jpg, you could use this code: 

<img alt="Travel reservations" src="travel . jpg" 

usemap="#mapl"> 
<map name="mapl"> 

</map> 

Inside the <ma p> tags you specify the various clickable regions of the image, as 
covered in the next section. 



Specifying clickable regions 



To specify an image map, a list of polygonal regions must be defined on an image and 
referenced in the HTML document. Three different types of polygons are supported: 
rectangle, circle, and free-form polygon. 

♦ rect — Defines a rectangle area by specifying the coordinates of the four corners 
of the rectangle. 

4- circle — Defines a circle area by specifying the coordinates of the center of the 
circle and the circle's radius. 

♦ poly — Defines a free-form polygon area by specifying the coordinates of each 
point of the polygon. 

Note that all coordinates of the image map are relative to the top-left corner of the 
image (effectively 0, 0) and are measured in pixels. For example, suppose you wanted 
an image for a travel site with a picture of a car, plane, and hotel. When the user 
clicks one of the pictures, they are taken to the right page for auto rentals, airfare, or 
hotel reservations. Such an image would resemble the image shown in Figure 6-8. 



| ^[J Travel Image Map Microsoft Internet Explorer 



-SB 



Filft F<lit VJew FiWrtritfis Toftls Hftlp 



.. ■ http : f/localhostf CtiapterOS/Fig]608 htTil 




^]Dcne 



\J Lcc^ it 



Figure 6-8: An image ready to be used as an image map. 



PI: JYS 

WY022-06 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



108 PartM ♦ HTML/XHTML Authoring Fundamentals 



The regions that can be used for the map are within the three icon squares (the 
white squares around the icons). The regions are all rectangular, uniform in size 
(121 pixels square), and have the following upper-left coordinates: 

♦ car — 35 x, 1 1 y 

♦ plane— 190 x, 11 y 

♦ hotel— 345 x, 1 1 y 

Knowing the upper-left corner coordinates and the size of each rectangle, you can 
easily figure out the coordinates of the bottom-right corner of each rectangle. 

Tip Several tools are available to help create image map coordinates. Use your 

favorite search engine to find a dedicated piece of software to map regions, 

' or examine your graphics program to see if it can create regions for you. Paint 

Shop Pro is an excellent Windows-based image editor that has image map tools 

built in. 

Specifying regions using anchor tags 

You can specify regions using anchor tags with shape and coords attributes. For 
example, to specify the three regions previously outlined, you could use the 
following: 

<map name="mapl"> 

<a href="pl ane . html " shape="rect" coords="35 , 11 , 156 , 1 3 2 " > 

Plane Reservati ons</a> 

<a href="car . html " shape="rect" coords="190 , 11 , 311 , 132 "> 

Rental Cars</a> 

<a href="hotel . html " shape="rect" coords="345 , 11 ,466 , 1 32" > 

Hotel Reservati ons</a> 

</map> 

Note that the link text helps the user determine what the clickable area leads to, as 
shown by the Internet Explorer ToolTip in Figure 6-9. 

Specifying regions using area tags 

Another way to define regions is by using <a rea > tags instead of anchors: 

<map name="mapl"> 
<area href="pl ane . html " 

shape="rect" coords="35,ll,156,132" 

alt="Plane Reservations") 
<area href="car . html " 

shape="rect" coords="190,ll,311,132" 

alt="Rental Cars") 
<area href="hotel . html " 

shape="rect" coords="345,ll,466,132" 

alt="Hotel Reservations") 
</map> 



PI: JYS 

WY022-06 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 1 Q9 



In the case of the <a rea > tag, using the a 1 1 attribute helps the user determine what 
the clickable area leads to, as shown by the Internet Explorer ToolTip in Figure 6-9. 



) Travel linage Map - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



0* & m $ 



Address |[) http://localhost/Chapter06/Fig0609.html 



B'EIB 



I 



H - 




J http://localho5t/Chapter06/plane.html 



\J Local intranet 



Figure 6-9: The link or a 1 1 text of a clickable region helps the user determine 
where the clicked region leads. 



Putting it all together 



A document with a working image map (as outlined in this section) would resemble 
the following code: 



IDOCTYPE HTML PUBLIC 


'-//W3C//DTD 


HTML 


4 


. 01// EN" 


" h 1 1 p : //www. w3.org/TR/html4/strict.dtd 


') 


html) 












head) 












<title)</title> 












/head) 












body) 












img alt="Travel Plans 


' src=" 


trave 


1 • jpg 


' 


jsemap="#mapl 


map name="mapl"> 












area href="pl ane . html 


' 










shape="rect" coords= 


•35,11, 


156,132" 






alt="Plane Reservations") 










area href="car . html " 












shape="rect" coords= 


•190,11 


,311, 


132" 






alt="Rental Cars") 












area href="hotel . html 


' 










shape="rect" coords= 


•345,11 


,466, 


132" 






alt="Hotel Reservations") 










/map) 












/body) 












/html) 













PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



10 Part II ♦ HTML/XHTML Authoring Fundamentals 



Note 



The image map example in this chapter is somewhat simplistic, using three 
identical rectangles for its regions. Image maps can be used for more complex 
purposes, such as the clickable U.S. map mentioned earlier in this chapter, 
allowing users to click various buildings on a map for more information, or 
parts on an exploded diagram of a machine. 



Animated Images 



The GIF format also supports rudimentary animation by showing different frames of 
an image one after another. The effect is similar to drawing individual frames of 
animation on different pages of a sketchbook and rapidly flipping the pages. 
Animated GIF images are not supported by all user agents and should be used 
sparingly due to their size — the image must store all the frames of the animation, 
increasing the size of the image. 

Some image editors include tools to help create animated GIF images, such as Jasc 
Software's Animation Shop, shown in Figure 6-10. 



Pfc Jasc Ahiin,tfiaii Sh op - CD SPIN 



~^jsm 



Edit View Animation Effects Window Hel|> 



»• ^ m D^asi 



*»iiiat s?x^ 



ail 



II t ► H \ -41 !► (5 



WH 



Jjf^Q +%~ j> j ,w & k / r\ 



[^ CD SPIN 


[1:1] - Frames 








S©@ 




r#j 


[] 


■ 


H 


H 


3 


F:1 D:10 


F:2 D:10 


F:3 D:10 


F4 D:10 


F:5 D:10 


r :6 D10 



For Help, press Fl 



6frarnes 75 :<: 75 0.60 tctal seconds (0.L0 second;) 



Figure 6-10: Programs such as Jasc Animation Shop can help you create animated GIFs, 
in this case the animation of a spinning CD-ROM. 



PI: JYS 
WY022-06 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



Chapter 6 ♦ Images 



Summary 



In this chapter, you learned the basics of image formats and how you can include 
them in your HTML documents. You learned the benefits and drawbacks of each 
supported format, as well as how to include and format them in an HTML document. 



Continue to read the chapters in order if you are new to HTML, learning each aspect 
of creating Web documents. If you are not new to HTML and you are particularly 
interested in media (images, video, and so on), check out Chapter 14. 



PI: JYS 

WY022-06 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:42 



112 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Links 



Links are what make the World Wide Web web-like. 
One document on the Web can link to several other 
documents, and those in turn to other documents, and so 
forth. The resulting structure, if diagramed, resembles a web. 
The comparison has spawned many "web" terms commonly 
used on the Internet — electronic robots that scour the Web are 
known as "spiders," and so on. 

Besides linking to other documents, you can link to just about 
any content that can be delivered over the Internet — media 
files, e-mail addresses, FTP sites, and so on. 

This chapter covers the ins and outs of linking to references 
inside and outside the current document and how to provide 
more information about the relationship of your documents to 
others on the Web. 



What's in a Link? 



Web links have two basic components, the link and the target. 

♦ The link is the text in the main document that refers to 
another document. 

4- The target is the document (or particular location in the 
document) to which the link leads. 



♦ ♦ ♦ ♦ 
In This Chapter 

What's in a Link? 

Linking to a Web Page 

Absolute versus Relative 
Links 

Link Targets and Titles 

Keyboard Shortcuts and 
Tab Order 

Creating an Anchor 

Choosing Link Colors 

The <link> Tag 

♦ ♦ ♦ ♦ 



For example, suppose a site on the Web reviews software. Each 
review includes a link to the manufacturer's Web site. Such an 
arrangement would resemble the diagram shown in Figure 7-1. 

The link has two components: a descriptor and a reference 
to the target. The target is a document that can be delivered 
via the Internet. In the preceding example, the review might 
list the manufacturer's name as the descriptor and the actual 
Web URL would be the reference. Both are specified in the 
anchor tag (<a >), as follows: 

<a href="url_of_target">descri ptor_text</a> 




113 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



114 Part II ♦ HTML/XHTML Authoring Fundamentals 



Review 

xyz Software 
Developed by xyz Inc 



xyz Inc 
Home Page 



Figure 7-1: The relationship of documents on the 
Web via links— the user clicks the link in the review 
document to reach the xyz Inc. home page. 

The target reference is specified via the href attribute, and the descriptor appears 
between the start and end anchor tags. For example, if the manufacturer is Acme 
Computers and its Web site is acme. example. com, the anchor tag would resemble 
the following: 

<a href="http : //www. exampl e . com">Acme Computer's Web Site</a> 

If you don't give the name of a document in the link, the Web server (in this case, 
www . exampl e . com) will send the defined top-level document (known as an index 
document) — typically, this document is named index. html or home. html. If such 
a document doesn't exist or one has not been defined for the server, an error will be 
returned to the client browser. 



Note 



The text "Acme Computer's Web Site" would be highlighted in the document to show 
it is a link. The default highlight for a link is a different color font and underlined, 
though you will see how to change the highlight later in this chapter. 

According to the "strict" HTML standard, anchor links need to be placed within 
block elements (headings, paragraphs, and so on). 



As mentioned in the introduction to this chapter, you can link to other things besides 
HTTP documents. All you need is the URL of the item you wish to link to, and the 
protocol necessary to reach the item. For example, if you wanted to link to a 
document on an FTP site, you could use an anchor tag similar to the following: 



<a href="ftp : //ftp . exampl e . com/pub/exampl e . zi p " > Z i pped copy of the fi 1 e s < / a > 

Note that the protocol is specified (f tp : instead of http :), and the server name is 
specified (f tp . exampl e . com), as is the path and filename (/pub and exampl e 
. z i p). A similar method can be used to link to an e-mail address 
(href="mai 1 to : someone@exampl e . com"). Clicking such a link will generally 
spawn the user's e-mail client ready to send an e-mail to the address specified. 



PI: JYS 

WY022-07 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Note The rest of this chapter concentrates on linking to other HTML documents on the 

Web. However, all the concepts addressed apply when linking to other content 
types. 



Linking to a Web Page 



The most popular link style on the Web is a link to another Web page or document. 
Such a link, when activated, causes the target page to load in the client browser. 
Control is then transferred to the target page — its scripts run, and so on. 

To link to another page on the Internet, you simply specify the target's URL in the 
anchor tag. Suppose you want to link to the products page of the Acme Web site and 
the page is named products . html and resides in the products directory on the 
Acme Web server. The href parameter of the link would be as follows: 

http : //www. example. com/products/ products. html 

Note that the URL (http : //acme . exampl e . com) contains the protocol, the server 
name, the directory name, and the filename. Figure 7-2 shows a breakdown of the 
various pieces of the URL. 



http:^www.example.com/products/products.html 



protocol I directory I 

server file/page 

Figure 7-2: The various pieces of a URL. 



In the case of this URL, the various pieces are separated by various key characters: 

♦ The protocol is first, and ends with a colon (http :). 

4- The server name is next, prefaced with a double slash (//www . exampl e . com). 

♦ The directory (or directories) is next, separated with slashes (/products/). 

♦ The filename of the page is last, separated from the directory by a slash 

(products . html). 

Note The server name is actually two pieces, the server's name and the domain 

on which it resides. In the www . exampl e . com, www is the server name and 
exampl e . com is the domain. 

There is a common misconception that all Web server names need to begin 
with www. Although www is a standard name for a Web server, the name can be 
almost anything. For example, the U.S.-based Web server for the Internet Movie 
Database (imdb . com) is us . imdb . com. 



Chapter 7 ♦ Links 115 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



16 Part II ♦ HTML/XHTML Authoring Fundamentals 



Absolute versus Relative Links 

There are two types of URL styles, and therefore two link types, that you need to 
understand: absolute and relative. You have seen absolute links, where the URL used 
in the link provides the full path, including the protocol and full server address. 
These links are called absolute links because the URL itself is absolute — that is, it 
does not change no matter where the document in which it appears is kept. 

The other type of link, a relative link, does not provide all of the details to the 
referenced page; hence, its address is treated as relative to the document where the 
link appears. Relative links are only useful for linking to other pages on the same Web 
site, because any reference off of the same site requires the remote server's name. 

It's easier to understand the difference between the two types of links with an 
example. Suppose you are the Webmaster of exampl e . com. You have several pages 
on the site, including the home page, a main products page, and hardware and 
software products pages. The home page is in the root directory of the server, while 
the product pages (all three) are in a products directory. The relative links back and 
forth between the pages are shown in Figures 7-3 and 7-4. 





Home 


Root Directory (/) 




If 


roducti 


/produc 


ts. htm 














^ 


' 




Products 




Products 




Directory 
(/products) 


./hard 


ware.ht 


ml 


,/S( 


3ftware.html 






i 


' 




' 


' 






Hardware 




Software 

















Figure 7-3: Relative links to subpages. 



Note that you can use directory shortcuts to specify where the pages are: 

♦ Starting a directory with a slash (/) references it as a subdirectory of the root 
directory. 

♦ Starting a directory with a period and a slash ( . /) references it as a 
subdirectory of the current directory (the directory where the current page 
resides). 

♦ Starting a directory with a double period and a slash (. . /) references it as a 
parent directory to the current directory. 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Chapter 7 ♦ Links 117 




Root Directory (/) 



../home. html 



Products 



/prod ucts.html T ./products.ht ml 



Products 
Directory 
(/products) 



Hardware 



Software 



Figure 7-4: Relative links to parent pages. 

Relative links are easier to maintain on sections of Web sites where the pages in that 
section never change relationships to one another. For example, in the case of the 
site shown in Figures 7-3 and 7-4, if the products pages move as a whole unit to 
another place on the site, the relative links between the product pages won't change. 
If the links were coded as absolute (for example, http : //www. example.com/ 
products/ha rdwa re. html), they would have to change. 



Link Targets 



Note 



Normally, links open the page they refer to in the active browser window, replacing 
the page currently displayed. However, you can control where the page opens using 
the target attribute in the link tag. 

The ta rget attribute has been deprecated in strict HTML. It appears here be- 
cause most browsers still support the attribute and it can be useful. However, 
keep in mind that your documents will not validate against strict HTML if you 
use the target attribute. 

The target attribute supports the values shown in Table 7-1. 



Table 7-1 
Target Attribute Values 



Value 

blank 
self 



Description 

Opens the linked document in a new browser window 
Opens the linked document in the same frame as the link 



Continued 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



18 Part II ♦ HTML/XHTML Authoring Fundamentals 



Value 



Table 7-1 (continued) 



Description 



parent Opens the linked document in the parent frameset 

top Opens the linked document in the main browser window, replacing 

any and all frames present 

name Opens the linked document in the window with the specified name 



For example, to open a linked document in a new window you would use a tag similar 
to the following: 

<a href="http : //www. exampl e . com" target="_bl ank"> 
New Window</a> 



Caution 



The debate about whether you should ever open a new window is fierce. Most 
users are accustomed to all new windows being of the pop-up ad variety— and 
very unwelcome. However, from a user interface standpoint, new windows can 
be used very effectively if they are used like dialog boxes or new windows that 
an operating system spawns. In any case, you should make a habit of informing 
users when you are going to open a new window so you don't surprise them. 



The last value listed for target, name, can also aid in the user interface experience, if 

used correctly. Certain methods of opening windows (such as the JavaScript 

wi ndow. open method) allow you to give a browser window a unique name. You can 

then use that name to push a linked document into that window. For example, the 

following code displays two links; the first opens a new, empty browser window 

named N EWS, and the second pushes the content at www . ya hoo . com into the 

window: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<script language="JavaScript"> 
function NewsWi ndow( ) { 

fln=wi ndow. open C"","N EWS", "wi dth=400 , hei ght=400" ) ; 
) 

</script> 
</head> 
<body> 

<p><a href="JavaScri pt : NewsWi ndow( ) ">0pen Wi ndow</a></p> 
<p><a href="http : //www. yahoo . com" target="NEWS">Fi 1 1 Wi ndow</a></p> 
</body> 
</html> 




For more information on JavaScript and the window, open method, refer to 
Chapter 25. 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Chapter 7 ♦ Links 119 



Link Titles 



You can also title a link, using the title attribute in the anchor tag. This causes 
most current browsers to display the text of the title as a ToolTip when the mouse 
hovers over them. For example, the following link will cause Internet Explorer 6 to 
display "Exampl e . corn's Web Site," as shown in Figure 7-5. 

More information can be found <a 

href="http : //www. exampl e . com" title=" Exampl e . com ' s Web 

Site">here</a>. 



g] http://localhost'Chapter07/fig7-5.htiiil - Micioso...B(j]S 



File Edit View Favorites Tools Help 

o • o ■ a i g|p * t els- 



Address :§j http://localhost/Chapter07/fio7-5,html 



H 



More information can be found here. 



| Example, corn's Web 5ite| 



1 http://www, example, com/ 



*j Local intranet 



Figure 7-5: The title attribute causes a ToolTip 
display when the mouse hovers over the link. 



You can use this feature to give the user more information on the link, before they 
click it. 



Keyboard Shortcuts and Tab Order 

In the modern world of computers it is easy to make assumptions about users, their 
hardware, and capabilities. Several years ago, no one would have dreamt of 
delivering rich, multimedia content over the Web. Today, however, it is easy to 
assume that everyone is using the latest browser, on a high-end computer, across a 
broadband connection. 



However, that isn't always the case. In fact, some users who visit your site may not 
even have a mouse to aid in browsing. The reason could be a physical handicap, a 
text-only browser, or just a fondness for using the keyboard. It is important to 



PI: JYS 

WY022-07 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



120 PartM ♦ HTML/XHTML Authoring Fundamentals 



accommodate these users by adding additional methods to access links on your 
page. 



Keyboard shortcuts 



Each link can be assigned a shortcut key for easy keyboard-only access using the 
accesskey attribute with the anchor tab. The accesskey attribute takes one letter 
as its value, the letter that can be used to access the link. For example, the following 
link defines "C" as the access key: 

<a href="http : //www. exampl e . com" access key="C">Tabl e of 
<b>C</b>ontents</a> 

Note that different browsers and different operating systems handle access keys 
differently. Some browser and operating system combinations require special keys 
to be pressed with the defined access key. For example, Windows users on Internet 
Explorer need to hold the Alt key while they press the access key. Note, also, that 
different browsers handle the actual access of the link differently — some browsers 
will activate the link as soon as the access key is pressed, while others only select 
the link, requiring another key to be pressed to actually activate the link. 

Tip Keyboard shortcuts won't help your users if you don't give them a clue as to 

,v what the shortcut is. In the example earlier in this section, the defined shortcut 

' key ("C") was used in the link text and highlighted using the bold font attribute. 



Tab order 



It will also help your users if you define a tab order for the links in your document. As 
with most graphical operating systems, the tab key can be used to move through 
elements of the interface, including links. 

Typically, the default tab order is the same as the order that the links appear in the 
document. However, upon occasion, you might wish to change the order using the 
t a b i n d e x attribute. The t a b i n d e x attribute takes an integer as its value; that 
integer is used to define the tab sequence in the document. For example, the 
following document switches the tab order of the second and third links: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

■•http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>Tab Ordered Document</ti tl e> 
</head> 
<body> 
<p>This is the <a href="http : //www. exampl e . com" 

tabindex="l">first link</a>.</p> 
< p > T h i s is the <a href="http : //www. exampl e . com" 

tabindex="3">second 1 ink</a>.</p> 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Chapter 7 ♦ Links 121 



Note 



C p > T h i s is the <a href="http : //www. exampl e . com" 

tabindex="2">third 1 i nk</a> . </p> 
;/body> 
;/html> 



As with most interface elements in HTML, the browser defines how tabi ndex 
is implemented and how tabbed elements are accessed. 



Creating an Anchor 



Anchor tags have another use; they can be used as a marker in the current document 
to provide a bookmark that can be directly linked to. For example, a large document 
might have several sections. You can place links at the top of the document (or in a 
special navigation frame) to each section, allowing the user to easily access each 
section. 

To create an anchor in a document, you use the anchor tag with the name attribute. For 
example, the following code creates achapterOl anchor at the "Chapter 1" heading: 



Chi) 



"chapterl">Chapter K/aX/hi; 



Note 



To link to the anchor you use a standard link, but add the anchor name to the end of 
the URL in the link. To identify the name as an anchor, you separate it from the rest 
of the URL with a pound sign (#). For example, suppose the Chapter 1 anchor 
appears in the document book. html. To link to the Chapter 1 anchor, you could use 
the following code: 

(a href="http : //www. exampl e . com/book . html#chapterl">Go to Chapter K/a> 

Because the URL in the link tag can contain the server and document names as 
well as the anchor name, you can link to anchors in the same document or any 
accessible document. If you are linking to an anchor in the same document, 
you can use a shortcut form of the URL, using only the pound sign and the 
anchor name as the URL. 



In addition to using the anchor tag for bookmarks, you can link to a block element's 
i d attribute. For example, if Chapter 1 appears inside an < h 1 > tag, you can set the 
< h 1 > tag's id attribute to Chapterl and omit the anchor link altogether, as shown in 
the following code example: 

<hl i d="chapterl">Chapter K/hl> 



Choosing Link Colors 



It is important that links stand out from the normal content in your documents. They 
need to be recognizable by users. Each link has four different status modes: 



PI: JYS 

WY022-07 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



122 PartM ♦ HTML/XHTML Authoring Fundamentals 



♦ Link — The standard link in the document that is not active, nor visited (see 
other modes). 

4 Active — The target of the link is active in another browser window. 

♦ Visited — The target of the link has been previously visited (typically, this means 
the target can be found in the browser's cache). 

4 Hover — The mouse pointer is over the link. 

Each of these modes should be colored differently so the user can tell the status of 
each link on your page. The standard colors of each link status are as follows: 

4 Link — Blue, underlined text 

4 Active — Red, underlined text 

4 Visited — Purple, underlined text 

4 Hover — No change in the appearance of the link (remains blue, red, or purple) 

Note As with other presentation attributes in HTML, the browser plays a significant 

role in setting link colors and text decorations. Most browsers follow the color 
scheme outlined in this section, but there are browsers that don't conform to 
this scheme. 

To change the text color and other attributes of links, you can modify the properties 
of each type of anchor tag. For example, the following style, when used in an HTML 
document, sets the default visited link text to bold and yellow: 

a:visited { color: yellow; font-weight: bold; I 

Tip Setting the properties of the anchor tag without specifying a mode changes all 

of the link modes to the characteristics of the style. For example, this style sets 



ui uie in lis. inuucb iu ii ic iiidiacLeiibiiLb ui uit 

all types of links (link, active, visited) to red: 



a { color: red ; } 

So why would you want to change the color of links in your document? One reason 
would be that the normal text of your document is the same color as the default link. 
For example, if your text is blue, you probably want to change the default color of 
the links in your document to better enable users to recognize them. 

It is a good idea to define all of the link attributes instead of haphazardly defining 
only one or two of the link status colors. The following styles define each type of link, 
ensuring they appear how you want in the document: 

a:link 1 color: #003366; 

font-family:verdana, palatino, arial, sans-serif; 

font-si ze:10pt; text-decoration: underline; 1 
a:visited {color: #D53D45; 

font-family:verdana, palatino, arial, sans-serif; 

font-si ze:10pt; text-decoration: underline; 1 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Chapter 7 ♦ Links 1 23 



a:active {color: #D53D00; 

font-family:verdana, palatino, arial, sans-serif; 

font-si ze:10pt; font- weight: bold; 

text -decorati on : underline; 1 
a:hover {color: # D 5 3 D 4 5 ; 

font-family:verdana, palatino, arial, sans-serif; 

font-si ze:10pt; text-decoration: none; ) 

Note the redundancy in the styles — there are only subtle changes in each style. You 
should strive to eliminate such redundancy whenever possible, relying instead upon 
the cascade effect of styles. You could effectively shorten each style by defining the 
anchor tag's attributes by itself, and defining only the attributes that are different for 
each variant: 

a { color: #003366; 

font-family:verdana, palatino, arial, sans-serif; 

f ont -si ze : lOpt ; text -decorati on : underline; ) 
a:visited {color: #D53D45; } 

a:active {color: # D 5 3 D ; font-weight: bold; ) 
a:hover {color: #053045; text-decoration: none; ) 



Link Target Details 



There are a host of other attributes that you can add to your anchor tags to describe 
the form of the target being linked to, the relationship between the current 
document and the target, and more. 

Table 7-2 lists these descriptive attributes and their possible values. 





Table 7-2 
Link Target Details 


Attribute 


Meaning 


Value(s) 


Charset 


The character encoding of the target 


char encoding 

for example, "ISO 8859-1" 


Href la ng 


The base language of the target 


language_code 

for example, "en-US" 



Rel 



The relationship between the current 
document and the target 



alternate 

designates 

stylesheet 

start 

next 

prev 

contents 



Continued 



PI: JYS 

WY022-07 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



124 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 7-2 (continued) 



Attribute 



Meaning 



Value(s) 



Rev 



The relationship between the target 
and the current document 



Type 



The MIME type of the target 



index 

glossary 

copyright 

chapter 

section 

subsection 

appendix 

help 

bookmark 

alternate 

designates 

stylesheet 

start 

next 

prev 

contents 

index 

glossary 

copyright 

chapter 

section 

subsection 

appendix 

help 

bookmark 

Any valid MIME type 



An example of how the relationship attributes (rel , rev) can be used is shown in 
the following code snippet: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>Chapter 10</title> 
</head> 
<body> 

<p><a href="contents . html " rel="chapter" rev="contents">Tabl e of 
Contents</aX/p> 

<p><a href="chapter9 . html " rel="next" rev="prev">Chapter 9</aX/p> 
<p><a href="chapter 11 . html " rel="prev" rev="next">Chapter ll</aX/p> 



The anchor tags define the relationships between the chapters (next, previous) and 
the table of contents (chapter, contents). 



PI: JYS 
WY022-07 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



Chapter 7 ♦ Links 1 25 



The Link Tag 



You can use the link tag to provide additional information on a document's 
relationship to other documents, independently of whether the current document 
actually links to other documents or not. The link tag supports the same attributes 
as the anchor tag, but with a slightly different syntax: 

♦ The link tag does not encapsulate any text. 
4- The link tag does not have an ending tag. 

For example, the following code could be used inchapterl0.html to define that 
document's relationship to chapter9 . html and chapterll . html : 

< 1 ink href="chapter9 . html " rel="next" rev="prev" /> 
< 1 ink href="chapterll . html " rel="prev" rev="next" /> 

The link tag does not result in any visible text being rendered, but can be used by 
user agents to provide additional navigation or other user-interface tools. 

Another important use of the link tag is to provide alternate content for search 
engines. For example, the following link references a French version of the current 
document (chapterlO . html): 

< L I N K lang="fr" re 1 =" a 1 ternate" hreflang="fr" 

href="http: //www. example. com/cha pterlO-fr.html" /> 

Other relationship attribute values (sta rt, contents, and so on) can likewise be 
used to provide relevant information on document relationships to search engines. 



Summary 



This chapter covered links — what they are and how to use them to reference other 
content on the Web. You learned how to construct a link and what attributes are 
available to the anchor and link tags. You also learned how to define relationships 
between your document and other documents, and why this is important. 

From here, you should progress through the next few chapters, familiarizing yourself 
with the other various pieces of an HTML document. 



PI: JYS 

WY022-07 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 9:44 



126 



P1:KTX 
WY022-08 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



Text 



CHAP 



E R 



Although the modern-day Web is a haven of multimedia, 
text is still vitally important. Only through text can 
some messages be succinctly communicated. Even then, 
diversity in text can help further clarify a message. For 
example, emphasizing one word with bold or italic font can 
change the tone and meaning of a sentence. 

This chapter discusses how to format elements inside of block 
elements (words or sentences inside of paragraphs). 



Methods of Text Control 



There are various means to control the look and formatting of 
text in your documents. It should come as no surprise that the 
more direct methods — <f ont> tags and the like — have been 
deprecated in favor of CSS controls in HTML 4.01 and XHTML. 
The following sections cover the various means possible for 
historical and completeness purposes. 






♦ ♦ ♦ ♦ 
In This Chapter 

Methods of Text Control 

Bold and Italic Text 

Monospace (Typewriter) 
Fonts 

Superscripts and Subscripts 

Abbreviations 

Marking Editorial Insertions 
and Deletions 

Grouping Inline Elements 
with the <span> Tag 



Tip Although it is sometimes easier to drop a direct format- 

,v ting tag into text, resist the urge and use styles instead. 
' Your documents will be more flexible and more stan- 
dards compliant. 



The <font> tag 



Note 



The <f ont> tag enables you to directly affect the size and 
color of text. Intuitively, the size attribute is used to change 
the size of text, and the color attribute is used to change the 
color. The size of the text is specified by a number, from 1-7, or 
by signed number (also 1-7). In the latter case, the size change 
is relative to the size set by the <basefont> tag. The 
<basefont> tag has one attribute, size, which can be set to a 
number, 1-7. 

Default font type and size is left up to the user agent. 
No standard correlation exists between the size used in 
a <f ont> tag and the actual font size used by the user 
agent. As such, the default size of the font (1-7) varies 
between user agents. 



127 



P1:KTX 
WY022-08 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



128 PartM ♦ HTML/XHTML Authoring Fundamentals 



For example, if you wanted larger text in a red color, you could use a tag similar to 
the following: 



(font size="+3" color="rec 



>this is larqer, red text</font> 



Note that using "+3" for the size increases the text within the tag by a factor of 3 from 
the base font size. 



Emphasis and other text tags 



You can use a handful of tags to emphasize portions of text. Although these tags 
have not been deprecated in HTML 4.01, it is strongly recommended that you make 
use of CSS instead. 

Table 8-1 lists the emphasis tags and their use. A sample of their use is shown in 
Figure 8-1. 





Table 8-1 
Emphasis Tags 




Tag 






Use 


<cite> 






Citation 


<code> 






Code text 


<dfn> 






Definition term 


<em> 






Emphasized text 


<kbd> 






Keyboard text 


<samp> 






Sample text 


<strong> 






Strongly emphasized text 



<var> 



Variable(s) 



The creation and adoption of these tags seems somewhat haphazard. As such, the 
support for the tags is not standard across user agents — you may not be able to tell 
the difference between text coded with <ci te> or <em>, for example. 



CSS text control 



CSS provides several different properties to control text. Table 8-2 lists some of the 
more popular properties. 

As you can see, CSS offers a bit more control over your text, allowing you to specify 
actual fonts and actual font sizes. However, the advantage to using CSS properties 
over hardcoded tags is not found in the list of available properties, but in the 
flexibility in formatting and effecting later changes. For example, suppose you were 



P1:KTX 
WY022-08 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



Chapter 8 ♦ Text 1 29 



@ Emphasis Tags - Microsoft Internet Explorer 








mfnlC^ 








File Edit View Favorites Tools Help 










o - m a 6|/> $ *- « 


®* 


||4 








Address 


Qhttp://localhost/Chapter08/fig8-l.htnnl 


^]H Go 


Standard test 








Citation 










Code text 










Definition term 










S'>.'l-i\ISiJ:.'J :■;'.'.': 










Keyboard text 










Sample text 










Strongly emphasized text 










Variable(s) 










SJDane 






^3 Local intranet 





Figure 8-1: An example of text using emphasis tags. 



Table 8-2 
CSS Text Properties 



Property 



Values 



color 


Color 


font 


font-style 




font-variant 




font-weight 




font-size 


font-family 


family-name 


font-size 


font-size 


font-stretch 


normal | wider | narrower | 




ultra-condensed | 




extra-condensed | condensed | 




semi-condensed | 




semi-expanded | expanded | 




extra-expanded | 




ultra-expanded 



Use 

Change the color of text 

Shortcut property for setting 
font style, variant, weight, and 
size 

Set the font family (face) 

Set the font size 

Expand or compress the letter 
spacing 



Continued 



P1:KTX 
WY022-08 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



1 30 Part " ♦ HTML/XHTML Authoring Fundamentals 



Table 8-2 (continued) 


Property 


Values 


Use 


font-style 


Normal | italic | oblique 


Set font to italic 


font-variant 


Normal | small-caps 


Set small-caps 


font-weight 


Normal | bold | bolder | lighter 


Set font to bold 


text-decoration 


none | underline | overline | 
line-through | blink 


Set under/overlining 


text-transform 


none | capitalize | uppercase | 
lowercase 


Transform font capitalization 



creating documentation for a programming language and wanted to format all 
reserved words a particular way — perhaps in a slightly larger, red, bold font. Using 
tags, the code would resemble the following: 



<p>The <font size="+l" color="red' 
function can be used to... 



(b>date</b></font) 



Later, you might decide that the red color is too much emphasis, and larger, bold text 
is enough. You must then change every <f ont> tag used around reserved words. 

Suppose, instead, that you used CSS, as shown in the following code: 

<head> 

<style type="text/css"> 

. reservedword { font: 14pt bold; colon: ned 1 

</style> 
</head> 
<body> 

<p>The <span cl ass="neservedword">date</span> function can 
be used to . . . 

If you later decided to change the formatting of reserved words, you would only have 
to make one change to the style definition at the top of the document. (If you used an 
external style sheet, that one change could change an unlimited number of 
documents that used the sheet.) 



Bold and Italic Text 



Two surviving text emphasis tags are bold and italic. Their effect on text is, as 
expected, to make it bold or italic, as shown in the following code example and in 
Figure 8-2: 



C p > T h i s is nonmal text.</p> 
:p><b>This is bold text .</b></p> 

Cp><i>This is italic t e x t . < / i > < / r 



P1:KTX 
WY022-08 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



Chapter 8 ♦ Text 131 



@ Bold and Italic - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 

q - -,j a in <& , p it m m !•&■ 



Address 



I http : //localhost/ChapterU8/f ig8-2 , html 



This is normal test. 
This is bold text. 

This is italic text. 



*J Local intranet 



Figure 8-2: Bold and italic tags at work. 



Note 



Not every font has a bold and/or italic variant. When possible, the user agent 
will substitute a similar font when bold or italic is asked for but not available. 
However, not all user agents are font-sawy. In short, your mileage with these 
tags may vary depending on the user agent being used. 

For the same reasons mentioned elsewhere, it is advisable to use CSS instead of 
hardcoded bold and italic tags. 



Monospace (Typewriter) Fonts 



Another text tag that has survived deprecation is the teletype (<tt>), or 
monospaced, tag. This tag tells the user agent that certain text should be rendered in 
a monospaced font. Such uses include reserved words in documentation, code 
listings, and so on. The following code shows an example of the teletype tag in use: 



<p>Consider using the <tt>date</tt> function instead. </p> 

This tag is named for the teletype terminals used with the first computers, which 
were only capable of printing in a monspaced font. 



P1:KTX 

WY022-08 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



1 32 Part II ♦ HTML/XHTML Authoring Fundamentals 



Tip Again, the use of styles is preferred over individual inline tags. If you need text 

rendered in a monospace font, consider directly specifying the font parameters 
using styles instead of relying upon the <tt> tag. 



\ 



Superscripts and Subscripts 



There are two tags, <sup> and <sub>, for formatting text in superscript and 
subscript. The following code shows an example of each tag, the output of which is 
shown in Figure 8-3. 

< p > T h i s is normal text.</p> 

< p > T h i s is the 16<sup>th</sup> day of the month. </p> 
<p>Waten tanks are cleanly manked as H<sub>2</sub>0 . </p> 



@ Superscript and Subscript - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 

o & a m 6 I -p * » © I .a * & i» -* 



Address ^J http://localhost/Chaptei-0S/fig8-3,htrnl 



This is normal test. 

;tH 



This is the 16 day of the month, (superscripted "th") 
Water tanks are clearly marked as IT,0. (subscripted "2") 



- T0 



t 



FIB' 



*J Local intranet 



Figure 8-3: Examples of superscript and subscript. 



Abbreviations 



You can use the abbreviation tag (<abbr>) to mark abbreviations and, optionally, 
give readers the expansion of the acronym used. For example, you could use this tag 
with acronyms such as HTML: 



<abbn ti tl e="Hypentext Markup Language">HTML</abbr> 



P1:KTX 

WY022-08 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



Chapter 8 ♦ Text 1 33 



Note that the expansion of the abbreviation is placed in the < a b b r > tag's title 
attribute. Some user agents will display the value of the title attribute when the 
mouse/pointer is over the abbreviation. 

Marking Editorial Insertions and Deletions 

To further strengthen the bond between HTML documents and printed material, 
the insert and delete tags have been added to HTML. Both tags are used for 
redlining documents — that is, a visually marked-up document showing suggested 
changes. 

For example, the following paragraph has been marked up with text to be inserted 
(underlined) and deleted (strikethrough). The output of this code is shown in 
Figure 8-4. 

<p>Peter <del>are</del><ins>is</ins> correct, the proposal 
from Acme is lacking a few <del>minor </del >detai 1 s . </p> 



@ Redlining Tags - Microsoft Internet Explorer 



- S)@ 



File Edit View Favorites Tools Help 

o - o h m fi I p i? m m 



m -$ 



Address %$ http://localhost/Chapter08/r"ig8-4,html 



St 
B 



Peter areis correct, the proposal from Acme is lacking a few mmor-details. 



^JDone 



\£ Local intranet 



Figure 8-4: The <i ns> and <del > tags can provide for suitable redlined 
documents. 



Note that the underline tag (<u>) has been deprecated in favor of the <i ns> tag. 



P1:KTX 
WY022-08 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 7:43 



1 34 Part II ♦ HTML/XHTML Authoring Fundamentals 

Grouping Inline Elements with 
the <span> Tag 

When using CSS for text formatting, you need a method to code text with the 
appropriate styles. If you are coding block elements, you can use the <d i v > tag to 
delimit the block, but with smaller chunks (inline elements) you should use <span>. 

The <span> tag is used like any other inline tag (<b>, <i >, <tt>, and so on), 
surrounding the text/elements that it should affect. You use the s ty 1 e or c 1 a s s 
attribute to define what style should be applied. For example, both of the following 
paragraph samples would render the word red in red text: 

<head> 

<style type="text/css"> 
.redtext { color: red; I 

</style> 
</head> 
<body> 

<!-- Paragraph 1, using direct style coding --> 
<p>We should paint the document <span styl e="col or : red") 
red</span> . </p> 

<!-- Paragraph 2, using a style class --> 

<p>We should paint the document <span cl ass="redtext"> 

red</span> . </p> 

</body> 

Of the two methods, the use of the class attribute is preferred over using the style 
attribute because class avoids directly (and individually) coding the text. Instead, 
it references a separate style definition that can be repurposed with other text. 



Summary 



This chapter covered the formatting of inline elements. You learned two distinct 
methods (direct tags and styles) and the various tags to supplement textual 
formatting. Keep in mind that you should use <d i v > or other block tags to format 
larger sections of a document. 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Special 
Characters 



Although its roots are firmly grounded in plain 
text, HTML needs to be able to display a wide range of 
characters — many that cannot be typed on a regular keyboard. 
Language is rich with extended and accented characters, and 
there are many reserved characters in HTML. 

The HTML specification defines many entities — specific 
codes — to insert special characters. This chapter introduces 
you to the concept of entities and lists the various entities 
available for use. 



Note 



The W3C Web site is a good source of information about 
entities. The HTML 4 entities are listed at http:// 
www. w3 . org/TR/h tin 1 4/sgml /entities, html. 



Understanding Character 
Encodings 



Note 



Character encoding at its simplest is the method that maps 
binary data to their proper character equivalents. For 
example, in a standard, U.S. English document character, 65 is 
matched to a capital A. 

Most English fonts follow the American Standard Code for 
Information Interchange (ASCII) coding. So when a Web designer 
inserts a capital A, he is assured that the user will see the A. 

There are, of course, plenty of caveats to that statement. The 
document must be encoded as English, the specified font must 
also be encoded as English, and the user agent must not 
interfere with either encoding. 

Document encoding is typically passed to the user agent 
in the Content- Type HTTP header, such as the follow- 
ing: 

Content -Type : text/html; charset=EN -US 




En and em Spaces and 
Dashes 

Copyright, Trademark, and 
Currency Symbols 

Real Quotation Marks 

Accented Characters 

Arrows and Greek and 
Mathematical Characters 

Other Useful Entities 

♦ ♦ ♦ ♦ 




135 



PI: JYS 

WY022-09 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



136 PartM ♦ HTML/XHTML Authoring Fundamentals 



However, some user agents don't correctly handle encoding in the HTTP header. 
If you need to explicitly declare a document's encoding, you should use an 
appropriate meta tag in your document, similar to the following: 

<meta http -equi v="Content -Type" content="text/html ; 
charset=EN-US"> 

So what happens when any of the necessary pieces are different or changed from 
what they were intended to be? For example, what if your document is viewed in 
Japan, where the requisite user agent font is in Japanese instead of English? In 
those cases, the document encoding helps ensure that the right characters are used. 

Most fonts have international characters encoded in them as well as their native 
character set. When a non-native encoding is specified, the user agent tries to use 
the appropriate characters in the appropriate font. If appropriate characters cannot 
be found in the current font, alternate fonts can be used. 

However, none of this can be accomplished if the document does not declare its 
encoding. Without knowing the document encoding the user agent simply uses the 
character that corresponds to the character position arriving in the data stream. For 
example, a capital A gets translated to whatever character is 65 f/i in the font the user 
agent is using. 



Special Characters 



Several characters mean special things in HTML and are used for special purposes 
by user agents. For example, the less than symbol (<) signals the beginning of a tag. 
As such, you cannot use that character in normal text. Instead, you must use an 
equivalent code, or entity. When the user agent renders the document, the entity is 
rendered as the correct character. 

Entities in HTML begin with an ampersand (&), end with a semicolon (;), and contain 
a numeric code or mnemonic phrase in between. 

Numerically coded entities can use decimal or hexadecimal numbers. Either must be 
preceded by a pound sign (#). Hexadecimal numbers also need to be preceded by an 
x. A nonbreaking space is character number 160. The following entity in decimal 
references this character: 

 

The following entity in hexadecimal also reference character 160: 

 

Mnemonic entities use a few characters to specify the entity — the characters usually 
are an abbreviation or mnemonic representation of the character they represent. For 
example, the following entity represents a nonbreaking space: 

&nbsp ; 

A few other essential entities are listed in Table 9-1. 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Chapter 9 ♦ Special Characters 1 37 







Table 9-1 
Essential Entities 




Decimal 


Entity 


Mnemonic Entity 


Character 


" 




Squot; 


Double quote mark 


& 




& 


Ampersand 


< 




< 


Less than symbol 


> 




> 


Greater than symbol 


 




Snbsp; 


Nonbreaking space 



Additional special-use characters are covered in the following sections. 



En and Em Spaces and Dashes 

There are two additional types of spaces and dashes, en and em spaces and dashes. 
The characters got their name from their relative size — en characters are as wide as 
a capital N, while em characters are as wide as a capital M. 

These characters have specific uses in the English language: 

4- En spaces are used when you need a larger space than a normal space 
provides. For example, en spaces can be used between street numbers and 
street names (123 Main) for clarity. 

4- Em spaces are used to separate elements such as dates and headlines, figure 
numbers and captions, and so on. (Figure 2-1 A simple prompt) 

♦ En dashes are used instead of hyphens in constructs such as phone numbers, 
element numbering, and so on. 

4- Em dashes are used grammatically when you need to divide thoughts in a 
sentence. (The excuse was nonsense — at least that's how it seemed to me) 

Table 9-2 lists the entities for en/em elements. 







Table 9-2 
En and Em Entities 




Decimal 


Entity 


Mnemonic Entity 


Character 


&#8194 




&ensp; 


En space 


&#8195 




&emsp; 


Em space 


&#8211 




Sndash; 


En dash 


&#8212 




&mdash; 


Em dash 



PI: JYS 

WY022-09 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



1 38 Part " ♦ HTML/XHTML Authoring Fundamentals 



Copyright and Trademark Symbols 

Copyright and trademark symbols are special symbols that indicate a legal 
relationship between individuals (or companies) and text. 

The Copyright symbol (©) is used to indicate that someone has asserted certain 
rights on written material — text included with the symbol usually indicates which 
rights. For example, many written works include the following phrase as a copyright: 
"Copyright © 2003. All rights reserved." 

The trademark and registered marks (™ and ®) are used to indicate that a particular 
word or phrase is trademarked — that is, marked (trademarked) or registered for 
unique use by an individual or company. For example, "Windows" is a registered 
trademark of Microsoft, and "For Dummies" is a registered trademark of Wiley. 

Note Trademark and registered trademark symbols are typically superscripted after 

the word or phrase to which they apply. As such, you should generally use each 
within superscripted (<sup>) tags. 

Table 9-3 lists the entities for Copyright, trademark, and registered symbols. 





Copyright, 


Table 9-3 
Trademark, and 


Registered Entities 




Decimal 


Entity 


Mnemonic Entity 


Character 




 




 


Copyright symbol 




 




 


Registered trademc 


irk symbol 



Note that there are fonts that include the trademark symbol (™). However, because 
the symbol is actually two characters, it is included as an exception, not a rule. As 
such, you shouldn't rely upon an entity to display the symbol, but specific small and 
superscript font coding such as the following: 

<smal 1 ><sup>TM</sup></smal 1 > 
Note Use of styles is generally preferred over the use of the <sma 1 1 > tag. 



Currency Symbols 



There are many currency symbols, including the U.S. dollar ($), the English pound 
(£), the European euro (€), and the Japanese yen (¥). There is also the general 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Chapter 9 ♦ Special Characters 1 39 



currency symbol (°). Table 9-4 lists many of the most common currency 
symbols. 







Table 9-4 
Currency Entities 




Decimal Entity 


Mnemonic 


Entity 


Character 


&#162 




 




The cent symbol (<t) 


&#163 




Spound; 




English pound 


&#164 




 




General currency 


&#165 




 




Japanese yen 


&#836 


*; 


&euro; 




European euro 



Note that the dollar symbol ($) is typically ASCII character 24 (in U.S. fonts) and can 
be accessed directly from the keyboard. 



// 



Real" Quotation Marks 



Real quotation marks, used in publishing, cannot be typed on a standard keyboard. 
The quote marks available on the keyboard (" and ') are straight quotes; that is, they 
are small, superscripted, vertical lines. 

Quote marks used in publishing typically resemble the numbers 6 and 9 — that is, 
dots with a serif leading off of them. For example, the following sentence is set off 
with real quote marks: 

"This sentence is a real quote." 

The opening quote marks resemble the number 6, closing quote marks resemble the 
number 9. Table 9-5 lists the entities for real quotes. 



Table 9-5 
Quote Mark and Apostrophe Entities 



Decimal Entity 



Mnemonic Entity 



Character 



&#8216; 
&#8217; 
&#8220; 
&#8221; 



&lsquo; 
&rsquo; 
&ldquo; 
&rdquo; 



Left/Opening single-quote 
Right/Closing single-quote and apostrophe 
Left/Opening double-quote 
Right/Closing double-quote 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



]40 PartM ♦ HTML/XHTML Authoring Fundamentals 



Arrows 

A variety of arrow symbols are available as entities. Table 9-6 lists these entities. 





Table 9-6 
Arrow Entities 




Decima, 


Entity Mnemonic Entity 


Character 


&#8592 


Slarr; 




Leftwards arrow 


&#8593 


&uarr; 




Upwards arrow 


&#8594 


&rarr; 




Rightwards arrow 


&#8595 


&darr; 




Downwards arrow 


&#8596 


&harr; 




Left right arrow 


&#8629 


&crarr 




Downwards arrow with 
corner leftwards 


&#8656 


&IArr; 




Leftwards double arrow 


&#8657 


&uArr; 




Upwards double arrow 


&#8658 


&rArr; 




Rightwards double arrow 


&#8659 


&dArr; 




Downwards double arrow 


&#8660 


&hArr; 




Left right double arrow 



Accented Characters 



There are many accented character entities available in the HTML standard. These 
characters can be used in words such as resume. Table 9-7 lists the accented 
character entities. 




Table 9-7 
Accented Character Entities 




Decimal Entity 


Mnemonic 


Entity 


Character 


&#192 




 




Latin capital letter A with grave 


&#193 




 




Latin capital letter A with acute 


&#194 




 




Latin capital letter A with circumflex 


&#195 




 




Latin capital letter A with tilde 


&#196 




 




Latin capital letter A with diaeresis 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Chapter 9 ♦ Special Characters 141 



Decimal Entity 



Mnemonic Entity 



Character 



&#197 


 Latin capital letter A with ring above 


&#198 


&AEIig; Latin capital letter AE 


&#199 


 Latin capital letter C with cedilla 


&#200 


SEgrave; Latin capital letter E with grave 


&#201 


 Latin capital letter E with acute 


&#202 


 Latin capital letter E with circumflex 


&#203 


 Latin capital letter E with diaeresis 


&#204 


&lgrave; Latin capital letter 1 with grave 


&#205 


&lacute; Latin capital letter 1 with acute 


&#206 


&lcirc; Latin capital letter 1 with circumflex 


&#207 


&luml; Latin capital letter 1 with diaeresis 


&#208 


 Latin capital letter ETH 


&#209 


 Latin capital letter N with tilde 


&#210 


 Latin capital letter with grave 


&#211 


 Latin capital letter with acute 


&#212 


 Latin capital letter with circumflex 


&#213 


 Latin capital letter with tilde 


&#214 


 Latin capital letter with diaeresis 


&#216 


 Latin capital letter with stroke 


&#217 


 Latin capital letter U with grave 


&#218 


 Latin capital letter U with acute 


&#219 


 Latin capital letter U with circumflex 


&#220 


 Latin capital letter U with diaeresis 


&#221 


 Latin capital letter Y with acute 


&#222 


 Latin capital letter THORN 


&#223 


 Latin small letter sharp s = ess-zed 


&#224 


 Latin small letter a with grave 


&#225 


 Latin small letter a with acute 


&#226 


 Latin small letter a with circumflex 


&#227 


 Latin small letter a with tilde 


&#228 


 Latin small letter a with diaeresis 



Continued 



PI: JYS 

WY022-09 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



142 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 9-7 (continued) 


Decimal Entity Mnemonic Entity Character 


&#229 


 Latin small letter a with ring above 


&#230 


 Latin small letter ae 


&#231 


 Latin small letter c with cedilla 


&#232 


Segrave; Latin small letter e with grave 


&#233 


 Latin small letter e with acute 


&#234 


 Latin small letter e with circumflex 


&#235 


 Latin small letter e with diaeresis 


&#236 


Sigrave; Latin small letter i with grave 


&#237 


 Latin small letter i with acute 


&#238 


 Latin small letter i with circumflex 


&#239 


 Latin small letter i with diaeresis 


&#240 


 Latin small letter eth 


&#241 


 Latin small letter n with tilde 


&#242 


Sograve; Latin small letter o with grave 


&#243 


 Latin small letter o with acute 


&#244 


 Latin small letter o with circumflex 


&#245 


 Latin small letter o with tilde 


&#246 


 Latin small letter o with diaeresis 


&#248 


 Latin small letter o with stroke 


&#249 


Sugrave; Latin small letter u with grave 


&#250 


 Latin small letter u with acute 


&#251 


 Latin small letter u with circumflex 


&#252 


 Latin small letter u with diaeresis 


&#253 


Syacute; Latin small letter y with acute 


&#254 


 Latin small letter thorn 


&#255 


 Latin small letter y with diaeresis 



Greek and Mathematical Characters 



Table 9-8 lists various Greek symbol entities. 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Chapter 9 ♦ Special Characters 1 43 





Table 9-8 
Greek Symbol Entities 




Decimal Entity Mnemonic Entity 


Character 


&#913 


SAIpha; 


Greek capital letter alpha 


&#914 


&Beta; 


Greek capital letter beta 


&#915 


&Gamma; 


Greek capital letter gamma 


&#916 


&Delta; 


Greek capital letter delta 


&#917 


SEpsilon; 


Greek capital letter epsilon 


&#918 


&Zeta; 


Greek capital letter zeta 


&#919 


&Eta; 


Greek capital letter eta 


&#920 


&Theta; 


Greek capital letter theta 


&#921 


Slota; 


Greek capital letter iota 


&#922 


SKappa; 


Greek capital letter kappa 


&#923 


SLambda; 


Greek capital letter lambda 


&#924 


&Mu; 


Greek capital letter mu 


&#925 


&Nu; 


Greek capital letter nu 


&#926 


&Xi; 


Greek capital letter xi 


&#927 


&Omicron; 


Greek capital letter omicron 


&#928 


&Pi; 


Greek capital letter pi 


&#929 


&Rho; 


Greek capital letter rho 


&#931 


&Sigma; 


Greek capital letter sigma 


&#932 


&Tau; 


Greek capital letter tau 


&#933 


SUpsilon; 


Greek capital letter upsilon 


&#934 


&Phi; 


Greek capital letter phi 


&#935 


&Chi; 


Greek capital letter chi 


&#936 


&Psi; 


Greek capital letter psi 


&#937 


&Omega; 


Greek capital letter omega 


&#945 


Salpha; 


Greek small letter alpha 


&#946 


&beta; 


Greek small letter beta 


&#947 


&gamma; 


Greek small letter gamma 


&#948 


&delta; 


Greek small letter delta 


&#949 


&epsilon; 


Greek small letter epsilon 



Continued 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



]44 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 9-8 (continued) 


Decimal Entity Mnemonic Entity 


Character 


&#950 


&zeta; 


Greek small letter zeta 


&#951 


&eta; 


Greek small letter eta 


&#952 


&theta; 


Greek small letter theta 


&#953 


Siota; 


Greek small letter iota 


&#954 


&kappa; 


Greek small letter kappa 


&#955 


Slambda; 


Greek small letter lambda 


&#956 


&mu; 


Greek small letter mu 


&#957 


&nu; 


Greek small letter nu 


&#958 


&xi; 


Greek small letter xi 


&#959 


&omicron; 


Greek small letter omicron 


&#960 


&pi; 


Greek small letter pi 


&#961 


&rho; 


Greek small letter rho 


&#962 


&sigmaf; 


Greek small letter final sigma 


&#963 


&sigma; 


Greek small letter sigma 


&#964 


&tau; 


Greek small letter tau 


&#965 


Supsilon; 


Greek small letter upsilon 


&#966 


&phi; 


Greek small letter phi 


&#967 


&chi; 


Greek small letter chi 


&#968 


&psi; 


Greek small letter psi 


&#969 


&omega; 


Greek small letter omega 


&#977 


&thetasym; 


Greek small letter theta symbol 


&#978 


&upsih; 


Greek upsilon with hook symbol 


&#982 


&piv; 


Greek pi symbol 



Table 9-9 lists a variety of mathematical symbols. 





Table 9-9 
Mathematical Symbol Entities 




Decimal Entity 


Mnemonic Entity 


Character/Symbol 


 


Stimes; 


Multiplication sign 



 



^division; 



Division sign 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Chapter 9 ♦ Special Characters ] 4 



Decimal Entity Mnemonic Entity 


Character/Symbol 


&#8704 


Sforall; 


For all 


&#8706 


&part; 


Partial differential 


&#8707 


Sexist; 


There exists 


&#8709 


Sempty; 


Empty set = null set = diameter 


&#8711 


&nabla; 


Nabla = backward difference 


&#8712 


&isin; 


Element of 


&#8713 


&notin; 


Not an element of 


&#8715 


&ni; 


Contains as member 


&#8719 


&prod; 


n-ary product = product sign 


&#8721 


&sum; 


n-ary summation 


&#8722 


&minus; 


Minus sign 


&#8727 


Slowast; 


Asterisk operator 


&#8730 


&radic; 


Square root = radical sign 


&#8733 


&prop; 


Proportional to 


&#8734 


&infin; 


Infinity 


&#8736 


&ang; 


Angle 


&#8743 


&and; 


Logical and = wedge 


&#8744 


&or; 


Logical or = vee 


&#8745 


&cap; 


Intersection = cap 


&#8746 


&cup; 


Union = cup 


&#8747 


&int; 


Integral 


&#8756 


&there4; 


Therefore 


&#8764 


&sim; 


Tilde operator = varies with = similar to 


&#8773 


&cong; 


Approximately equal to 


&#8776 


Sasymp; 


Almost equal to = asymptotic to 


&#8800 


; &ne; 


Not equal to 


&#8801 


Sequiv; 


Identical to 


&#8804 


; &le; 


Less than or equal to 


&#8805 


; &ge; 


Greater than or equal to 


&#8834 


&sub; 


Subset of 


&#8835 


&sup; 


Superset of 



Continued 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



]46 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 9-9 (continued) 


Decimal 


' Entity Mnemonic 


Entity 


Character/Symbol 


&#8836 


&nsub; 




Not a subset of 


&#8838 


&sube; 




Subset of or equal to 


&#8839 


&supe; 




Superset of or equal to 


&#8853 


Soplus; 




Circled plus = direct sum 


&#8855 


&otimes; 




Circled times = vector product 


&#8869 


&perp; 




Up tack = orthogonal to = perpendicular 


&#8901 


&sdot; 




Dot operator 


&#8968 


&lceil; 




Left ceiling 


&#8969 


&rceil; 




Right ceiling 


&#8970 


&lfloor; 




Left floor 


&#8971 


&rfloor; 




Right floor 


&#9001 


&lang; 




Left-pointing angle bracket 


&#9002 


&rang; 




Right-pointing angle bracket 



Other Useful Entities 



Table 9-10 lists other miscellaneous entities. 





Table 9-10 
Miscellaneous Entities 


Decimal Entity Mnemonic 


Entity 


Character/Symbol 


&#161 


 




Inverted exclamation mark 


&#166 


 




Broken bar= broken vertical bar 


&#167 


 




Section sign 


&#168 


 




Diaeresis = spacing diaeresis 


&#170 


 




Feminine ordinal indicator 


&#171 


Slaquo; 




Left-pointing double angle quotation 
mark = left pointing guillemet 


&#172 


 




Not sign 


&#173 


 




Soft hyphen = discretionary hyphen 


&#175 


 




Macron = spacing macron = overline = 
APL overbar 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



Chapter 9 ♦ Special Characters 1 47 



Decimal Entity 


Mnemonic Entity 


Character/Symbol 


 


 


Degree sign 


 


Splusmn; 


Plus-minus sign = plus-or-minus 
sign 


 


 


Superscript two = superscript digit 
two = squared 


 


 


Superscript three = superscript 
digit three = cubed 


 


 


Acute accent = spacing acute 


 


 


Micro sign 


 


Spara; 


Pilcrow sign = paragraph sign 


 


Smiddot; 


Middle dot = Georgian comma = 
Greek middle dot 


 


Scedil; 


Cedilla = spacing cedilla 


 


Ssupl; 


Superscript one = superscript digit 
one 


 


 


Masculine ordinal indicator 


 


 


Right-pointing double angle 



quotation mark= right pointing 
guillemet 



 


&fracl4; 


Vulgar fraction one quarter = 
fraction one quarter 


 


&fracl2; 


Vulgar fraction one half = fraction 
one half 


 


 


Vulgar fraction three quarters = 
fraction three quarters 


 


 


Inverted question mark = turned 
question mark 


&#338; 


SOEIig; 


Latin capital ligature OE 


&#339; 


&oelig; 


Latin small ligature oe 


&#352; 


&Scaron; 


Latin capital letter S with caron 


&#353; 


&scaron; 


Latin small letter s with caron 


&#376; 


&Yuml; 


Latin capital letter Y with diaeresis 


&#710; 


Scire; 


Modifier letter circumflex accent 


&#732; 


&tilde; 


Small tilde 



Thin space 

Continued 



PI: JYS 
WY022-09 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:44 



148 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 9-10 (continued) 


Decimal 


' Entity Mnemonic 


Entity 


Character/Symbol 


&#8204 


&zwnj; 




Zero width non-joiner 


&#8205 


&zwj; 




Zero width joiner 


&#8206 


&lrm; 




Left-to-right mark 


&#8207 


&rlm; 




Right-to-left mark 


&#8218 


&sbquo; 




Single low-9 quotation mark 


&#8222 


&bdquo; 




Double low-9 quotation mark 


&#8224 


&dagger; 




Dagger 


&#8225 


&Dagger; 




Double dagger 


&#8240 


&permil; 




Per mille sign 


&#8249 


&lsaquo; 




Single left-pointing angle quotation mark 


&#8250 


&rsaquo; 




Single right-pointing angle quotation mark 



Summary 



Although most of your Web documents will contain standard characters, there are 
times when you need accented or special characters as well. Taking character and 
language encoding into account, you can also fall back on HTML entities to insert 
these special characters. 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Tables 



Tables are a powerful HTML tool that can be used in many 
ways. Developed originally to help communicate tabular 
data (usually scientific or academic-based data), tables are 
now used for many purposes, including actual page design. 
This chapter covers the basics of tables. 



Parts of an HTML Table 

An HTML table is made up of the following parts: 

4- Rows 

♦ Columns 

♦ Header cells 

♦ Body cells 

♦ Caption 

♦ Header row(s) 

♦ Body row(s) 

♦ Footer row(s) 



Figure 10-1 shows an example of an HTML table with the 
various parts labeled. 

The table shown in Figure 10-1 is defined by the following code: 

< 1 D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>A HTML Tabl e</ti tl e> 
</head> 
<body> 

<table border="l"> 

<caption>Table Caption</caption> 
<thead> 

<tr><td colspan="2">Table Header</tdX/tr> 
</thead> 







♦ ♦ ♦ ♦ 

In This Chapter 

Parts of an HTML Table 
Table Width and Alignment 
Cell Spacing and Padding 
Borders and Rules 
Rows and Cells 
Table Captions 
Grouping Rows 
Background Colors 



Spanning Columns 
and Rows 

Grouping Columns 

♦ ♦ ♦ ♦ 







149 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



150 PartM ♦ HTML/XHTML Authoring Fundamentals 



<tfoot> 

<tr><td colspan="2">Table Footer</tdX/t r> 
</tfoot> 
<tbody> 

<tr><th>Header Cell K/thXth>Header Cell 2</thX/tr) 
<trXtd>Body Cell K/tdXtd>Body Cell 2</tdX/tr> 
</tbody> 
</table> 
;/body> 
;/html> 



g A HTML Table - Microsoft Internet E... Q(n)Q 


File Edit View Favorites Tools " 


o * j a id : <* 


Address 


© http://localho5t/ChapterlO/FiglO- [v 


a^o 


Table Caption 






|Table Header 




|Header CeU 1 [Header CeU 2 


|Body Cell 1 |Body Cell 2 


|Table Footer 






^§J Done \J Local intranet 



Figure 10-1: HTML table elements. 

Many parts of the HTML table are optional — you only need to delimit the table (with 
<ta bl e> tags) and define rows (via <t r> tags) and columns (via <td> tags). Such a 
minimum table would resemble the following: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

< t i 1 1 e > A HTML Tabl e</t i tl e> 
</head> 
<body> 

<table border="l"> 

<trXtd>Body Cell K/tdXtd>Body Cell 2</tdX/tr> 

</table> 
</body> 
</html> 



Tip 



It is possible to nest tables within one another. In fact, a particularly popu- 
lar HTML technique— using tables for layout (covered in the next chapter- 
depends on this ability. Tables must be nested within table cells (<td> tags). 
See the Cells section later in this chapter for more information on the <td> 
tag. 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 151 



Table Width and Alignment 



Typically, an HTML table expands to accommodate the contents of its cells. For 
example, consider the following code and the resulting tables shown in Figure 10-2: 



C ! D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
;html> 
;head> 

<title>HTML Table Wi dths</ti tl e> 
;/head> 
;body> 

; P > 

Short Text Table<br /> 
<table border="l"> 

<tr><td>Short Text K/tdXtd>Short Text 2</tdX/tr> 
</table> 
;/p> 

; P > 

Longer Text Table<br /> 

<table border="l"> 

<tr><td>Longer Text K/tdXtd>Longer Text 2</tdX/tr) 

</table> 
;/p> 
;/body> 
;/html> 



Short Text Table 



Short Text 1 Short Text 2 



Figure 10-2: HTML tables expand to accommodate their 
content. 



Longer Text Table 



Longer Text 1 Longer Text 2 



Once a table expands to the limits of its container object — whether the browser 
window, another table, or sized frame — the contents of the cells will wrap, as shown 
in Figure 10-3. 

Sometimes you will want to manually size a table, either to fill a larger space or to 
constrain the table's size. Using the width attribute in the < t a b 1 e > tag you can set a 
table's size by specifying the table width in pixels or a percentage of the containing 
object. 

For example, if you specify "50%" as in the following code, the table's width will be 
50% of the containing object, as shown in Figure 10-4. 



1D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4. 01// EK 
"http://www.w3.org/TR/html4/strict.dtd"> 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



1 52 Part II ♦ HTML/XHTML Authoring Fundamentals 



|jT] HTML Tahls WHths Microsoft I ntemat Exp I orar 



bjiia 



rile Edit View favorites Tools H*l|> 

O - O • IE «i -P**« 



i- a im -a 



iddress $|Q h:tp : |/Iocalho:t10iap:e' 1 J7 z ig 10-3 .htm 



"BH° 



The Declaration of 
Independence 



IN COHC-EE33, Jtdy 4, 177.3. 

The unanimous Declaration of the thirteen united States of America, 

Wncnin die Course of human events, it bccorr.es necessary for one people :c dissolve die political 
bands which have connected them ;vrth another, and to assume among the powers of the earth, the 
separate and ecual station to which the Laws of Nature and of Nature 1 : God entitle them, a decent 
r2£pectto die opinions of mankind requires that they should declare the causes which impel diem to 
the seoaration. 

W? hold these truths to he sell-evident, tha: all men are created equal, that they ar? endowed by 
their Creator witb certain lnahenabe bight?, tha: among these are 1 ite. Liberty and die pursm: ot 
H£ppin5£s.--That to secure thsse rignts. Governments are hstitu:ed among \Cem deriving thsir just 
powers from the ;or.ser.t 0: th.5 governed. --That whenever any Form of Government tec ones 
destructive of these ends, it is TheBigh: of the People to alter or to aboishit. and to institute nsw 
Government, laying its foundation on such principles and crgamzing its powers in such form, ai :o 
them shall seem most likely to effect Their Safety and Happiness. Prudence, indeed, will dictate that 
Governments luti^ established should noL be jhan^td foi Lj=J:iL tnd liantitii, ctuita. and aucoidin^y 
all e&pemiiLue hitli alitwu, dial mankind ait iuoie disponed Lo suflei, wlrlt evils at e suflei tble, diau 
to right themselves by abolishing the forms to which they ai*c accustomed. But when a long tram of 
abuse; and usurpations, pursung mvanaby the same Object ;vmces a design to /educe them unde." 
absolute Despotism, it is thcr right, it is their duty, to throw off such Government, ar.dto provide 
new Guards for their future security. Such has been the patient sufferance of these Colonies; and 
such is now the necessity which constrains thsrn to aber dieir formal Systems of Gsvernmen:. The 



Figure 10-3: Cell contents wrap if a table cannot expand any further. 



*j Lo:cJ intranet 






- 



\^\ 59% TaMe WMth - Microsoft Internet Explorsr 
File Edit View Favorites T>>ols Help 



■ m 



O - O • is] ; , ■ * e 



0* & m a 



Addogs | jjj) nttp;j/locjho5t/Cha:.tc:(in/=ic.1u l.htn 



~F1B' : 



:ck Tabic Wieii 



ell 



Cell 2 



Cdl3 



C : 114 



g Cons 



*J Local intranet 



Figure 10-4: A 50% width table occupies 50% of the available width. 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 53 



Chtml> 
;head> 
<title>502 Table Wi dth</ti tl e> 

;/head> 
;body> 

; P > 

50X Table Width<br /> 
<table border="l" width="50X"> 
<tr><td>Cell K/tdXtd>Cell 
<td>Cell 3</tdXtd>Cell 
</table> 
;/p> 
;/body> 
;/html> 



2</td) 
4</td) 



:/tr> 



Note 



Note 



Besides specifying the width of the full table, you can also specify the width 
of each column within the table, using width attributes in <th> and <td> 
tags, or specifying width within <col> or <colgroup> tags. These tech- 
niques are covered in the "Cells" and "Grouping Columns" sections later in this 
chapter. 

Using a percentage in the width attribute allows the table to size itself dynamically to 
the size of its container. For example, if a table is set to 50%, the table will display as 
50% of the browser window, whatever size the window happens to be. 

If you need to specify the exact width of a table, you should specify the width of the 
table in pixels instead. For example, if you need a table to be 400 pixels wide, you 
would specify the table with the following tag: 

<table width="400px"> 

However, what happens if the specified width exceeds the table's container object? If 
the container is scroll-bar enabled (like a browser window), horizontal scroll bars 
will appear to allow the user to scroll the entire table. For example, consider the 
table shown in Figure 10-5. 

If the table's specified width exceeds the container's width, and the container is 
not scrollbar enabled, it is up to the browser to handle the table. Most browsers 
will resize the table to fit the width of its container. 

The <ta bl e> tag also supports the a 1 i gn attribute, which controls where the table 
is positioned in the containing element. The align attribute supports 1 eft, ri ght, 
and center values — the table's position is appropriately adjusted by the setting of 
this attribute. Note that this attribute has no visible effect on a table that occupies 
the full width of its container object. 



Cell Spacing and Padding 



There are two cell spacing options — padding and spacing — that you can control in 
your HTML tables. Cell spacing is the space between cells. Cell padding is the space 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



] 54 Part II ♦ HTML/XHTML Authoring Fundamentals 



ffi HTML Table Widths - Microsoft Internet Explorer 



- -iQ 



File Edit View Favorites Tools Help 



o-e'BHj<aLp&«fei0i'& 



$ 



Address |g] http://localhost/ChapterlO/Fig 10-5. htm 



Go 



The Declaration of 
Independence 



E[ 



m CONGRESS, July 4, 1776. 

The unanimous Declaration of the thirteen united Stat 

When in the Course of human events, it becomes nee 
which have connected them with another, and to as si 
and equal station to which the Laws of Nature and ol 
opinions of mankind requires that they should declare 

We hold these truths to be self-evident, that all men e 
Creator with certain unalienable Eights, that among tl 
-That to secure these rights, Governments are institut 
consent of the governed, --That whenever any Form 
it is the Eight of the People to alter or to abolish it, ar 
on such principles and organizing its powers in such f 
Safety and Happiness. Prudence, indeed, will dictate 
changed for light and transient causes; and according 
disposed to suffer, while evils are suflferable, than to iQ 

a 



Done 



\i Local intranet 



Figure 10-5: Tables too wide for their environment can get some help from 
scrollbars. 



between the cell border and its contents. Refer back to Figure 10-1 for the 
relationship of cell padding and cell spacing to the table. 

Cell spacing is controlled with the cellspacing attribute and can be specified in 
pixels or percentages. When specified by percentage, the browser uses half of the 
specified percentage for each side of the cell. The percentage is of the available 
space for the dimension, vertical or horizontal. This is illustrated in Figure 10-6, 
where the table's cell spacing is set to 20%. 

Cell padding is controlled with the cellpadding attribute. As with cell spacing, you 
can specify padding in pixels or a percentage. 



T 'P Keep in mind that cell spacing and cell padding can have a drastic effect on the 

\ available size for cell content. Increasing both spacing and padding decreases 
the cell content size. 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 55 



g] http://localhost'Chapter10/Fig10^.htm - Microsoft Internet Explorer EBB 
File Edit View Favorites Tools Help 

O - O • IS & I P ■&tf€»|[S T &B-$ 




Figure 10-6: Cell spacing percentages. 



Borders and Rules 

The border around HTML tables and in between cells can be configured in many 
ways. The following sections cover the various ways you can configure table borders 
and rules. 



Table borders 



You can use the border attribute of the <tabl e> tag to configure the outside border 
of the table. For example, consider the following code containing three tables and 
the resulting output in Figure 10-7. 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>Table Outside Borders</ti tl e> 
</head> 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



156 PartM ♦ HTML/XHTML Authoring Fundamentals 



<body) 



No Borders<br /> 
<table border="0"> 

<tr><td>Cell K/td) 
<tr><td>Cell 3</td) 
</table> 

:/p> 



:td>Cell 2</td) 
:td>Cell 4</td) 



:/tr) 
:/tr) 



border = Kbr /> 
(table border="l' 
<tr><td>Cell 
<tr><td>Cell 
(/table) 



;/p> 



K/td) 
3</td) 



:td>Cell 
:td>Cell 



2</td) 
4</td) 



:/tr) 
:/tr) 



riorder = 5<br /> 
(table border="5' 
<trXtd>Cell 



<tr) 
</table) 

P> 

body) 
html> 



(td>Cell 



K/td) 
3</td) 



(td>Cell 
:td>Cell 



2</td) 
4</td) 



:/tr) 
:/tr) 



g] Table Outside Borders - Microsoft In... EBB 



File Edit View Favorites Tools 



If 



o-o- a a «ii-p *# 



Address g) http://lccalriostfChapterirj/ARfFig[y1 H Go 



No Borders 
Cell 1 Cell 2 
Cell 3 Cell 4 



Border 


= 1 


Cell 1 Cell 2 


Cell 3 


Cell 4 


Border = 5 


Cell 1 Cell 2 


Cell 3 


Cell 4 



©Done 



\j Local intranet 



Figure 10-7: Examples of table border 
widths. 



The border attribute's value specifies the width of the border in pixels. The default 
border width is 0, or no border. 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 57 



T 'P Borders are an effective troubleshooting tool when dealing with table problems 

\ in HTML. If you are having trouble determining what is causing a problem in 

a table, try turning on the borders to better visualize the individual rows and 

columns. If you are using nested tables, turn on the borders of tables individually 

until you narrow down the scope of the problem. 

To specify which outside borders are displayed, use the frame attribute with one of 
the values displayed in Table 10-1. 





Table 10-1 
Values to Use with the Frame Attribute 


Value 


Definition 


Void 


Display no borders 


Above 


Display a border on the top of the table only 


Below 


Display a border on the bottom of the table only 


Hsides 


Display borders on the horizontal sides (top and bottom) only 


Ihs or rhs 


Display only the left side or the right side border only 


Vsides 


Display borders on the vertical sides (right and left) only 


box or border 


Display borders on all sides of the table (the default when border 
attribute is set without specifying frame) 



Note 



Not all user agents follow the defaults for table borders (no borders, or 
box/border when a border width is specified). If you want a table to show up 
with particular formatting, take care to specify all options. 



Table rules 

You can use the rul es attribute of the <tabl e> tag to control what rules (borders 
between cells) are displayed in a table. Table 10-2 shows the rules attribute's 
possible values. 

Note that the width of rules is governed by the table spacing attribute. For example, 
setting cellspacing to a value of 5px results in rules 5 pixels wide. 



Rows 



Table rows are the horizontal elements of the table grid and are delimited with 
table row tags (<t r >). For example, a table with five rows would use the following 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



1 58 Part " ♦ HTML/XHTML Authoring Fundamentals 



pseudocode: 






<table> 






<tr> row 


1 


</tr 


<tr> row 


2 


</tr 


<tr> row 


3 


</tr 


<tr> row 


4 


</tr 


<tr> row 


5 


</tr 


</table> 









Table 10-2 
Possible Rules Attribute Values 


Value 


Definition 


none 


Display no rules 


groups 


Display rules between row groups and column groups only 


rows 


Display rules between rows only 


cols 


Display rules between columns only 


all 


Rules will appear between all rows and columns 



The rows are divided into individual cells by embedded <td> or <th> tags (see the 
next section, "Cells," for more details). 



Note 



The row ending tag (</tr>) is optional. However, for clarity in your code you 
should consider always including appropriate ending tags. 



The <t r> tag supports the following attributes shown in Table 10-3. 



Table 10-3 
Tag Attributes 



Attribute Definition 



Align Set to right, 1 eft, center, just i fy, or char, this attribute controls the 

horizontal alignment of data in the row. Note that if you use char alignment, 
you should also specify the alignment character with the char attribute 
described below. 

Char Specifies the alignment character to use with character (char) alignment 

Charoff Specifies the offset from the alignment character to align the data on. Can be 

specified in pixels or percentage 

Valign Set to top, mi ddl e, bottom, or basel i ne, this attribute controls the vertical 

alignment of data in the row. Baseline vertical alignment aligns the baseline of 
the text across the cells in the row 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 59 



For an example of how baseline vertical alignment differs from bottom alignment, 
consider the two tables in Figure 10-8. 



Bottom Alignment 



text 



justify 



Figure 10-8: Baseline alignment aligns the baseline of the text. 



Baseline Alignment 



text 



justify 



If you use the alignment attributes in a <t r> tag, that alignment will be applied to 
all cells in that row. To format cell alignment individually, specify the alignment 
attribute(s) in individual cell tags (<th> or<td>)orin <col> or <colgroup> 
tags. 



Note 



The bgcol or attribute, used to set the background color for the row, has been 
deprecated in HTML 4.01. Instead of using this attribute, it is recommended 
that you use applicable styles to accomplish the same effect. 



Cells 



Individual cells of a table are the elements that actually hold data. In HTML, cell 
definitions also define the columns for the table. You delimit cells/columns with table 
data tags (<td>). 

For example, consider the following code: 

<table border="l" eel 1 paddi ng="5"> 
<tr> 

<td>Column K/tdXtd>Col umn 2</tdXtd>Col umn 3</td> 
</tr> 
<tr> 

<td>Col limn K/tdXtd>Col umn 2</tdXtd>Col umn 3</td> 
</tr> 
</table> 



T 'P Formatting your tables with ample white space (line breaks and indents) will 

help you accurately format and understand your tables. There are just as many 
ways to format a table in HTML as there are Web programmers— find a style 
that suits your taste and stick to it. 

This code defines a table with two rows and three columns, due to the three sets of 
<td> tags. 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



160 PartM ♦ HTML/XHTML Authoring Fundamentals 



You can also use table header tags (<th>) to define columns that are headers for the 
columns. Expanding on the previous example, the following adds column headers: 

<table border="l" eel 1 paddi ng="5"> 
<tr> 

<th>Header K/thXth>Header 2</thXth>Header 3</th> 
</tr> 
<tr> 

<td>Column K/tdXtd>Col umn 2</tdXtd>Col umn 3</td> 
</tr> 
<tr> 

<td>Column K/tdXtd>Col umn 2</tdXtd>Col umn 3</td> 
</tr> 
</table> 

Table header tags make it easy to format column headings, without having to result 
to character formatting. For example, the preceding code results in most user agents 
rendering the < t h > cells in a bold font (the default for < t h >). To accomplish the 
same formatting without header tags, you would need to include bold character 
formatting similar to the following: 



(tn> 
<th> 
<th) 
<th> 

(/tn> 



>Header K/bX/th) 
>Header 2</bX/th) 
>Header 3</bX/th> 



Note 



Note 



Using CSS, your formatting options with <th> are practically limitless; simply define 
appropriate formatting or several formatting classes as necessary. 

Most user agents will not properly render an empty cell (for example, 
<td></td>). When you find yourself needing an empty cell, get in the habit 
of placing a nonbreaking space entity () in the cell (for example, 
<td> </td>) to help ensure the user agent will render your table 
correctly. 

Although cells represent the smallest element in a table, surprisingly, they have the 
most attributes for their tags. Supported attributes include those shown in Table 10-4. 

Previous versions of HTML also supported a nowrap attribute to control 
whether a cell's contents wrapped or not. In HTML 4.01 , this attribute has been 
deprecated in favor of styles. See Chapters 1 6 and 1 7 for more information on 
styles. 



Table Captions 



Table captions (<capti on>) provide an easy method to add descriptive text to a 
table. For example, suppose you wanted to caption a table detailing the refresh rates 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 



Table 10-4 
Cell Attributes 



Attribute 



Definition 



Abbr An abbreviated form of the cell's contents. User agents can use the 

abbreviation where appropriate (speaking a short form of the contents, 
displaying on a small device, and so on). As such, the value of the abbr 
attribute should be as short and concise as possible 

Align The horizontal alignment of the cell's contents— left, center, right, justify, or 

char (character) 

Axis Used to define a conceptual category for the cell, which can be used to 

place the cell's contents into dimensional space. How the categories are 
used (if at all) is up to the individual user agent 

Char The character used to align the cell's content if the alignment is set to char 

Charoff The offset from the alignment character to use when aligning the cell 

content by character 

Colspan How many columns the cell should span (default 1). See the Spanning 

Columns and Rows section for more information 

Headers A space-separated list of header cell i d attributes that corresponds with 

the cells used as headers for the current cell. User agents use this 
information at their discretion— a verbal agent might read the contents of 
all header cells before the current cell's content 

rowspan How many rows the cell should span (default 1). See the Spanning 

Columns and Rows section for more information 

Scope The scope of the current cell's contents when used as a header— row, col 

(column), rowgroup, colgroup (column group). If set, the cell's contents 
are treated as a header for the corresponding element(s) 

Valign The vertical alignment of the cell's contents— top, middle, bottom, or 

baseline 



of a monitor. The following code adds an appropriate caption to a table, whose 
output is shown in Figure 10-9. 



(ID0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd"> 

(html) 

(head) 

<title>Monitor Sett ings</ti tie) 

(/head) 

(table border="l" eel 1 paddi ng="3" eel 1 spaci ng="2' : 

(capti on)Supported Refresh Rates</capti on) 

(tr> 

<th)H Resolution</thXth)V 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



162 PartM ♦ HTML/XHTML Authoring Fundamentals 



Resolution</thXth>Frequency</th> 

</tr> 

<tr> 

<td>640</td><td>480</td><td>60 to 120 Hz</td> 
</tr> 
<tr> 

<td>800</td><td>600</td><td>55 to 110 Hz</td> 
</tr> 
<tr> 

<td>832</td><td>624</td><td>55 to 106 Hz</td> 
</tr> 
<tr> 

<td>1024</td><td>768</td><td>55 to 87 Hz</td> 
</tr> 
<tr> 

<td>1152</tdXtd>870</tdXtd>55 to 77 Hz</td> 
</tr> 
<tr> 

<td>1280</td><td>1024</td><td>55 to 66 Hz</td) 
</tr> 
</table> 
</body> 
</html> 



^\ Monitor Settings - Microsoft Internet Explorer 



QSQ 



File Edit View Fiivorites Tools Help 



Address g] http://localhost/ChapterlO/FiglO-8.hcm 



^] Hgq 



Supported Refresh Rates 



H Resolution 


V Resolution 


Frequency 


640 


480 


60 to 120 Hz 


800 


600 


55 to 110 Hz 


832 


624 


55 to 106 Hz 


1024 


768 


55 to 87 Hz 


1152 


870 


55 to 77 Hz 


1280 


1024 


55 to 66 Hz 









*j Local intranet 



Figure 10-9: Captions ("Supported Refresh Rates" in this example) 
are displayed above the table. 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 63 




Note that the <caption> tag must appear immediately after the <tabl e> tag. 
Captions typically appear centered above the table to which they are 
attached — although different user agents may interpret the caption differently. 

You can use styles to format the caption however you like. For more information 
on styles, see Chapters 16 and 17. 



Row Groupings— Header, Body, and Footer 

Simple tables only have one section, the body, which consists of rows and columns. 
However, you might want to include additional information in your table by defining 
a table header and footer to complement the information in the body. 

For example, the header could contain the header rows, the body could contain the 
data, and the footer totals for each column. The advantage to breaking up the table 
into the three sections is that some user agents will then allow the user to scroll the 
body of the table separately from the header and footer. 

Note The HTML 4.01 specification dictates that you must use all three sections- 

header, body, and footer— if you use any. You cannot use only a header and 
body section without a footer, for example. If you don't intend to use one of 
the elements, you must still include tags for the section, even if the section is 
otherwise empty. 

The table header is delimited by<thead> tags — otherwise, its content is exactly like 
any other table section, delimited by <t r>, <td>, and optionally <th> tags. For 
example, consider the following table header section: 

<thead> 

<tr><th>Name</thXth>Hire Date</thXth>Ti tl e</thX/tr> 
</thead> 

Other than being delimited by <tbody> tags, the table body is defined and 
formatted just like any other table element. The table footer is delimited by<tfoot> 
tags and is formatted like the other two sections. 

Tip Although it seems counterintuitive, you should place the <tf oot> section 

■^ before the <tbody> section in your code to allow the user agent to correctly 
■'' anticipate the footer section and appropriately format the <tbody > section. 

All three section tags support align and valign tags for controlling text alignment 
within the section. (The char and cha rof f attributes are also supported for 

al i gn="cha r".) 

For an example of a table with all three sections, consider the following code and its 
output, shown in Figure 10-10. 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



164 PartM ♦ HTML/XHTML Authoring Fundamentals 



I Page Estimates - Microsoft Internet Explorer 



B(5)B 



File Edit View Favorites Tools Help 

Q - Q ■ \*\ & '&\ P i? *t &\ @- 



a 



S S 



Address ^ http://localhost/ChapterlO/FiglO-09.htm 



Chapter 


Pages 


Figures 


Illustrations 


1 
2 
3 
4 


10 
12 

9 
20 



4 
2 
7 


2 
1 

3 


Totals 


51 


13 


6 



VI 



*j Local intranet 



Figure 10-10: The three table sections (header, body, footer) can be set 
off by custom rules. 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>Page Estimates</ti tl e> 
</head> 
<body> 
<table border="l" eel 1 paddi ng="3" eel 1 spaci ng="2" 

rul es="groups"> 
<thead al i gn="center"> 

<tr> 

<th>Chapter</th><th>Pages</thXth>Figures</th> 
<th>Illustrations</th> 

</tr> 
</thead> 
<tToot al i gn="center"> 

<tr> 

<td>Totals</td><td>5K/td><td>13</tdXtd>6</td) 

</tr> 
</tfoot> 
<tbody al i gn="center"> 

<tr> 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 65 



<td>K/tdXtd>10</tdXtd>0</tdXtd>2</td> 
</tr> 
<tr> 

<td>2</tdXtd>12</tdXtd>4</tdXtd>K/td> 
</tr> 
<tr> 

<td>3</tdXtd>9</tdXtd>2</tdXtd>0</td> 
</tr> 
<tr> 

<td>4</tdXtd>20</tdXtd>7</tdXtd>3</td) 
</tr> 
;/tbody> 
;/table> 
;/body> 
;/html> 



Note how the three sections are set off by rules, but the table is otherwise devoid of 
rules. This is because of the rules = " groups" attribute in the <tabl e> tag. Also 
note how alignment attributes are used in the section tags to center the text in the 
table. 



Background Colors 



In previous versions of HTML, you could use the bgcolor attribute in the <tabl e>, 
and <tr>, <th>, and <td> tags to set a color background for the element. This 
attribute has been deprecated in HTML 4.01 in favor of using styles to set the 
background color of table elements. 

Using the deprecated method, you can set the background of a header row to yellow 
with code similar to the following: 

<tr bgcol or="yel 1 ow"> 

<th>H Resolution</th> 

<th>V Resolution</th> 

<th>Frequency</th> 
</tr> 

Using CSS to accomplish the same effect would resemble the following code (output 
is shown in Figure 10-11). 



<tr styl e="background -col or : 
<th>H Resolution</th> 
<th>V Resolution</th> 
<th>Frequency</th> 

</tr> 



yellow;' 



However, not all user agents adequately support background colors in tables. Older 
browsers are particularly finicky about correctly representing background colors. 
When in doubt, test. 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



166 PartM ♦ HTML/XHTML Authoring Fundamentals 



^] Monitor Settings - Microsoft Internet Explorer 



- -i ■-. 



File Edit View Favorites Tools Help 

H Q - 53 & i P * * « I © * 



B $ 



Address 



|http://localhost/Chapterl0/Figl0-10.htm 



I 



yj Q Go 



Supported Refresh Rates 



H Resolution 


V Resolution 


Frequency 


640 


480 


60 to 120 Hz 


800 


600 


55 to 110 Hz- 


832 


624 


55 to 106 Hz 


1024 


768 


55 to 87 Hz 


1152 


870 


55 to 77 Hz 


1280 


1024 


55 to 66 Hz 






\j Local intranet 



Figure 10-11: Use the background-color CSS property to control table 
element backgrounds. 



Spanning Columns and Rows 

It is possible to span data cells across multiple columns and rows using the col span 
and rows pa n attributes. Usually such spanning is used to provide column or row 
headings for groups of columns. For example, consider the following table code and 
the resulting output shown in Figure 10-12. 



(table border="l" eel 1 paddi ng="5"> 

(capti on>Respondent Summary to Questions 1 -4</capti on> 

<tr al i gn="center"> 

<th>Category</th> 

<thXge</thXth>#l</thXth>#2</thXth>#3</thXth>#4</th> 



</tr 

<tr) 



(td rowspan="3">Male<br>Respondents</td> 
(!-- Above cell spans 3 rows --> 
(td>23</td><td>A</td><td>C</tdXtd>F</td) 



:td>B</td) 



:/tr> 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 67 



Respondent Summary - Microsoft Internet Explorer 



- -i£ 



File Edit View Favorites Tools Help 



I 



4 



Address 



I http: //localhost/Chapter 1 0/Fig 1 0- 1 1 . htm 



Respondent Summary to Questions 1-4 



Category 




Age 


#1 


#2 


#3 


s4 




23 


A 


C 


F 


B 


Male 
Respondents 


29 


B 


F 


A 


A 




25 


C 


C 


C 


C 


Female 
Respondents 


23 


F 


E 


B 


B 


21 


B 


B 


B 


A 


23 


F 


F 


C 


C 



v ej go 



§)Done 



^J Local intranet 



Figure 10-12: You can span cells across both columns and rows. 



<tr> 

< ! - - First cell is the span cell - - > 

<td>29</td><td>B</tdXtd>F</td><td>A</tdXtd>A</td) 
</tr> 
<tr> 

< ! - - First cell is the span cell - - > 

<td>25</td><td>C</tdXtd>C</td><td>C</tdXtd>C</td) 
</tr> 

<!-- End of first span --> 
<tr> 

<td rowspan="3">Female<br>Respondents</td> 

<!-- Above cell spans 3 rows --> 

<td>28</tdXtd>F</tdXtd>E</tdXtd>B</tdXtd>B</td) 
</tr> 
<tr> 

< ! - - First cell is the span cell - - > 

<td>2K/tdXtd>B</tdXtd>B</tdXtd>B</tdXtd>A</td> 
</tr> 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



168 PartM ♦ HTML/XHTML Authoring Fundamentals 



<tr> 

< ! - - First cell is the span cell - - > 

<td>23</td><td>F</td><td>F</td><td>C</tdXtd>C</td> 
</tr> 

</table> 

Note that the rows that include a previously spanned cell omit the declaration of 
their first cell. 

You can span columns using the col span attribute in a similar fashion, as shown in 
the following code and resulting output in Figure 10-13. 



^F] Respondent Summary - Miciosoft Internet Explorer 



B@Q 



File Edit View Favorites Tools Help 



* 



O - <D - B E tf> \P * # 



&" & B % 



Address @ http://localhost7Chapterl0/Figl0-12.htm 



EH' 



<N 



Respondent Summary by Answer 





Aggressive 


Passive 


Pas sive Aggie s sive 


Respondent 


A 


B 


C 


D 


E 


F 


Mike 





3 


4 





5 


2 


Terri 








4 


6 


2 


2 


Amy 


7 


7 














Ted 


2 


2 


4 


2 


2 


2 


Thomas 


7 


3 


4 











Corinna 








4 


10 












*j Local intranet 



Figure 10-13: Spanning columns with the col s pan attribute. 



(table border="l" eel 1 paddi ng="5"> 

(capti on>Respondent Summary by Answer</capt i on) 

<tr al i gn="center"> 

< ! - - Spanning group headers - - > 

<th></th> 

<th colspan="2" wi dth="150">Aggressi ve</th> 

<th colspan="2" wi dth="150">Passi ve</th> 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 1 69 



<th colspan="2" wi dth="150">Passi ve/Aggressi ve</th> 
</tr> 
<tr ali gn="center"> 

<!-- Individual column headens --> 

<th>Respondent</th><th>A</th><th>B</th> 

<th>C</th><th>D</th><th>E</thXth>F</th> 
</tr> 

<! -- Table data --> 
<tn> 

<td>Mike</td> 

<td>0</td><td>3</td><td>4</td> 

<td>0</td><td>5</td><td>2</td> 
</tr> 

<td>Tenri</td> 

<td>0</td><td>0</td><td>4</td> 

<td>6</td><td>2</td><td>2</td> 
</tr> 

<td>Amy</td> 

<td>7</td><td>7</td><td>0</td> 

<td>0</td><td>0</td><td>0</td> 
</tr> 

<td>Ted</td> 

<td>2</td><td>2</td><td>4</td> 

<td>2</td><td>2</td><td>2</td> 
</tr> 

<td>Thomas</td> 

<td>7</td><td>3</td><td>4</td> 

<td>0</td><td>0</td><td>0</td> 
</tr> 

<td>Coninna</td> 

<td>0</td><td>0</td><td>4</td> 

<td>10</td><td>0</td><td>0</td> 
</table> 

You can also span columns and rows within the same table by using appropriate 
col span and rows pan attributes. However, such use is not recommended without a 
GUI HTML editor, because the code becomes exponentially complex the more 
customizations you make to a table. 

Cross- A For more information on GUI HTML editors, see Chapter 35. 
Reference 



Grouping Columns 



HTML 4.01 has added a few extra tags to make defining and formatting groups of 
columns easier. The two tags, <col group) and <col >, are used together to define 
and optionally format column groups and individual columns. 



The <col group> tag is used to define and optionally format groups of columns . The 
tag supports the same formatting attributes as the <tr> and <td>/<th> tags 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



170 PartM ♦ HTML/XHTML Authoring Fundamentals 



(al i gn, val i gn, wi dth, and so on). Any columns defined by the <col group) will 
inherit the formatting contained in the <colgroup> tag. 

To define columns in a group, use the span attribute with the <colgroup> tag to 
indicate how many columns are in the group. For example, the following HTML table 
code places the first three columns in a group: 

<table> 

<colgroup span="3"> 

</col group> 



Note that additional <col group> tags can be used to create additional column 
groups. You must use additional column groups if the columns you are grouping are 
not contiguous or do not start with the first column. For example, the following 
HTML table code creates three column groups: 

♦ Columns 1 and 2, formatted with centered alignment 

♦ Columns 3-5, formatted with decimal alignment 

♦ Columns 6-10, formatted with right alignment and bold text 

<table> 

<colgroup span="2" al i gn="center"> 

<!-- This group contains columns 1 & 2 --> 

</col group> 

<colgroup span="3" align="char" char="."> 

<!-- This group contains columns 3 - 5 --> 

</col group> 

<colgroup span="5" al i gn="ri ght" styl e="Tont -wei ght : bold;" > 

<!-- This group contains columns 6 - 10 --> 

</col group> 

Note Column groups that do not have explicit formatting attributes defined in their 

respective <col group) tags inherit the standard formatting of columns within 
the table. However, the group is still defined as a group and will respond ac- 
cordingly to table attributes that affect groups (rul es="groups", and so on). 

What if you don't want all the columns within the group formatted identically? For 
example, in a group of three columns, suppose you wanted the center column 
(column number 2 in the group) to be formatted with bold text? That's where the 
<col > tag comes into play, defining individual columns within the group. For 
example, to format a group using the preceding example (middle column bold), you 
could use code similar to the following: 

<table> 

<colgroup span="3"> 

<!-- This group contains columns 1 & 3 --> 

<col></col> 

<col styl e="Tont -wei ght : bold;"X/col> 



PI: JYS 
WY022-10 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



Chapter 10 ♦ Tables 



(colX/col) 
(/col group) 



The < c o 1 > tag follows similar rules to that of the <col group> tag, namely the 
following: 

♦ Empty tags (those without explicit formatting) are simply placeholders. 

4- You must define columns in order, and in a contiguous group, using blank 
< c o 1 > tags where necessary. 

♦ Missing or empty <col > tags result in the corresponding columns inheriting 
the standard formatting for columns in the table. 

Note that in standard HTML the < c o 1 > tag has no closing tag. However, in XHMTL 
the < c o 1 > tag must be closed by a corresponding < / c o 1 > tag. 

Tip Column definitions via the <col group) or <col > tags do not eliminate or 

v change the necessity of <td> tags (which actually form the columns). You 
'' must still take care in placing your <td> tags to ensure proper data positioning 
within columns. 



Summary 



This chapter covered the basics of HTML tables. You learned how to define a table, 
what the various pieces of a table were and what each is used for, and how to format 
the various elements of a table. 



Because of their diversity, it is impossible to cover all uses of tables. However, given 
enough time and imagination, each Web designer will find several uses for 
tables — including page design, as covered in the next chapter. 



PI: JYS 

WY022-10 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:47 



172 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Page Layout 
with Tables 



C HlA P T 



Tables are one of the most flexible elements in HTML. 
As such, they can be used for much more than displaying 
tabular data. In fact, they have become one of the mainstays of 
document formatting and page layout for the Web. 

This chapter covers how to use tables to achieve simple and 
complex formatting and layout results. 



Rudimentary Formatting 
with Tables 

It's not hard to see how tables can help with formatting 
elements on a local level. For example, consider the following 
code and the output shown in Figure 11-1. 



♦ ♦ ♦ ♦ 

In This Chapter 

Rudimentary Formatting 
with Tables 

Real-World Examples 

Floating Page 

Odd Graphic and Text 
Combinations 

Navigational Menus and 
Blocks 

Multiple Columns 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd"> 

<html> 

<head> 

<ti t 1 e>Simpl e Form</title> 

</head> 

<body> 

<f orm> 

<p>Name : &nbsp ; <i nput type="text" si ze="40"X/p> 

<p>Age : &nbsp ; 

<input type="radio" name="20to30" val ue="20to30"> 

20-30 

<input type="radio" name="31to40" val ue="31to40"> 

31-40 

<input type="radio" name="41to50" val ue="41to50"> 

41-50 

</p> 

</f orm> 

</body> 

</html> 



173 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



174 PartM ♦ HTML/XHTML Authoring Fundamentals 



@ Simple Form - Microsoft Internet Explorer 



B@Q 



File Edit View Favorites Tools Help 



/' 



o - o - a e ■£ p ti 9 % 0- §» m % 



Address sg] http://localhost/Chapterl 1/Figl 1-1 .htm 



HB< 



Name: 



Age: O 20-30 O 31-40 O 41-50 



y j Local intranet 



Figure 11-1: A rudimentary form using spaces for layout purposes. 

A simple table can help better align the elements in this form, as shown in the 
following code and Figure 11-2. 



< 1 D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd"> 

<html> 

<head> 

<ti tl e>Rudimenta ry Form Al i gnment</ti tl e> 

</head> 

<body> 

<f orm> 

<table width="50%" border="l"> 

<tr> 

<td width="25%"Xp>Name:</pX/td> 

<td><pXinput type="text" si ze="40"X/pX/td> 

</tr> 

<tr> 

<td><p>Age:</pX/td> 

<td><p> 

<input type="radio" name="20to30" val ue="20to30"> 

8.nbsp;20-30 

<input type="radio" name="31to40" val ue="31to40"> 

8.nbsp;31-40 

<input type="radio" name="41to50" val ue="41to50"> 

8<nbsp;41-50 

</p></td> 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 1 75 



(/table) 
;/f orm> 
;/body> 
;/html> 



^J Rudimentary Form Alignment - Microsoft Internet Explorer 



- nQ 



File Edit View Favorites Tools Hel|> 

o- a • E U ^ Pi?*© 

Address I @ http : //localhost/Chapter 1 1 /Fig 1 1 -2 . htm 



IB -$ 



"BET 



Name: Q 


Age: 20-30 31-40 41-50 





^Done 



\f Local intranet 



Figure 1 1-2: Aligning the labels and fields in a form using a simple table. 

However, this serves only to line up the labels and fields in two columns. This is 
better than no alignment, but if you add a nested table, you can add more order to 
the radio buttons, as shown in the following code and Figure 11-3. 

<!D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<ti t 1 e>Formatti rg with Nested Tabl es</ti tl e> 
</head> 
<body> 
<f orm> 

<table wi d t h=" 50% " border="l"> 
<tr> 

<td width="25S"Xp>Name:</pX/td> 
<td><p><input type="text" si ze="40"X/pX/td> 
</tr> 
<tr> 

<tdXp>Age:</pX/td> 
<td> 



(table wi dt h=" 100% " border="l' 
(tr> 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



176 PartM ♦ HTML/XHTML Authoring Fundamentals 



<td><pXinput type="radio" name="20to3C 

value="20to30"X/pX/td> 

<tdXpXi nput type="radio" name="31to4C 

value="31to40"X/pX/td> 

<tdXpXinput type="radio" name="41to5C 

value="41to50"X/pX/td> 

</tr> 

<tr> 

<tdXp>20-30</pX/td> 

<tdXp>31-40</pX/td> 

<td><p>41-50</p></td> 

</tr> 

</table> 

</td> 
</table> 
</f orm> 
</body> 
</html> 



§ Formattinjj with Nested Tables - Microsoft Internet Explorer 



Q@S 



File Edit View Favorites Tools Help 



O ■• O ' iU 



p**e S'&i-a 



,;. . http : //localhost/Chapted 1 /Fig 11-3, htm 



a 



Name: 




Age: 


o 


o 


o 


|20-30 


31-40 41-50 



^1 



\j Local intranet 



Figure 1 1-3: Nested tables allow for even more alignment and formatting control. 



Note 



Of course, in real life the tables in the examples would have even more format- 
ting attributes to fine-tune the alignment, and the borders would be off or set 
to accent the formatting. 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 1 ~J~I 



Even though these examples are fairly small in scope, it should be easy to see 
the power and flexibility tables can lend to alignment, formatting, and even page 
layout. 



Real-World Examples 



You might be surprised at how many tables are hiding under the veneer of the Web 
pages you frequent. For example, take a look at Figure 11-4, which shows a corporate 
Web site. 



'-"- ! Y i o < | c-ny : I h* Linux P I inVi in C c- n 1 1> any - f/1 i c i «"S oft 1 1 itc- i n+1 L ?■ p I -n i *i 



, =, *; 



HI* Frllr Wew rfiv-irlTfifi Trs&la Hf.I|> 

© - O - 3 B tf P # « « I &-■■ fc K -4 




Debian Project celebrates 
a decade 

]r 1333, a cc — pi.ter sc erce stucert at Purdja 
LrivRK^iTy nFimprd Tnn Murrlnnk ^Frt =i m = = = FrjF ii rl-F 
i;j u.Jz. iriij^iiJu^uluuiiiuriL i twturLVJ. 

pn ypflr^ IfltFr, I Fin M irrdnrv ■=; m-f ni jr r f r Finrd r:i Ft 
Ll ul- ir luluur uffiuu uf PrLi^Li y. <_i J Jiu L.uLijuu. uf Ll ■_. 
first message, a new Linux di=tuution ca lee Debian 
k ■ mii-Trr: iy tinu^inrk if vi mmr ^nfrw f m 
uy v ylurjyrt.~riy CdJ = n 3- uiuu. ridt niduy turjt.dnLi=l 
r:i iti-ini it r r ^ n "dip nnpr -=:ri.r~fi fit inuM 
CD-i - L.rtcs CL-rrj ihot encode, incLJ. re ^hc 
adept en d~ a c c mmunit/-r: e = e c dauelcpmert — Dda _ 
thF ■rFFiii ifrhF H = iri iFir:L'Fir] f ^y^tRrn (rliikrjj,. Find 
the lonstcrt reminder tmi the st-cngth cf Jnux \s :hc 
"d.Lt v t.yiM' duunu ■■_ -= ■ l- lu.Lr t |_ 1-= ■_ jiii i_tdl . 



Need a customized Linux 
platform? 



*■ Linux is tie platform ct choice "D-Irtamet 
inf rF -=fri jrfr \yf., infrwrr^ ipv = ni — ft, Finrd hirjh- 
IL 1 1" j ■ 1 1 idr MJzi .uiiipuL i i_ diJ •: =u.:y bid.irm i'lLu 
r e y/ ta -rite r e s, f rs — = erua-appliaices tD zorsD-ate 
ccslitcps, 

^rngeny k n = l = ^d ij r d = i =nriftiir rriv nprnf 
LiriuH uldJurin Ld-ririiJuu v . u viLi l - u Lri=i = 
cecade ot expererce buildng Lri.:< sokitions, 
rrzgnny s Linux : : :■': ponce rid a number cf tic 
LdJinUumut dnU bytL uduLuut L I" i = L = I dJd Jiy 
I iniiH hid"FinF tid=Hy. jmnrfij 

Frsgany s Plnttann Sei^vices is ai alien - et ye to 
til 'rrr d?r> fr c , .il " I ii vs. d tHi rinn. nlnrfrr- 
Stiviuyt Ju v iJdt d jliiiuli ti JjbL- _inuH 
rkrrih.t rn iiFir ran lift r: j^-nmi - f r: =^ = ily Finrd 



- 



jjm. 



^JLLLdi Lldl^ 



Figure 11-4: A corporate Web site that doesn't visibly use tables. 



Figure 11-5 shows the same Web site with the table borders on. Note the multitude of 
nested tables used to achieve the layout. 

Figure 11-6 shows another popular layout format, a floating page and two columns of 
content. Again, note that the use of tables (visible in Figure 11-7) isn't readily 
apparent. 



The rest of this chapter shows you how to achieve some of these effects. 



PI: JYS 
WY022-11 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



178 PartM ♦ HTML/XHTML Authoring Fundamentals 



hi ■ tf-i ny: lit- Li mm.-. HldUoiin '.^nit|i.iiiy Mi ■_ i wj ll lnl+nn-1 t>.|»ki?i 



rtfe Edit View ravorft«i Tools H«l|i 

O * O *1 ill til P & tf 48 I d ~; & 




:<= |j§ liU^.VLLdliLnl,-: ic^ctLi/Ptumji -jjHUJuli^Uj-UV 



Debian Project celebrates 
a decade 



:-w-£ 



±10. 



[r L533. du. iuL..t 



= nud tLui-dr L ■=. F jr Juu 



^nmr"." 



jm.H=vf ipr=[ 



=W^f|T Jf 



Tir •;(-■..-"-, |,]-f, rrn Mi . nin ■: ( h m ininnr ird rJiir- 
:e:hic ogy Dff ice r c- Proc ar y , and die subject of :l- at 
ist rnessaqa, a raw i_nu:< distribi.:icn called Uebion, 
= sup jc tad n? ticjsends d\ voUrieer EDhVena 
jLVjlui_Jr.i "I J DuL jn "TujllLMjj iiijJl juLj.^iLjI 
■^nnrt—ih - irin i^ tn ■+■ n rpnr ^ninr irri I inn: 
?ornrrunfc as c.ir ng d-ia: decede. ic .icing the 
acopt d\- Dt a corr -iur r*oe s ad dej el du ner: racel, 
:l _ a ere at d\- Dftiie Cabal packecie syjiein (Jjtg^. and 
■!■= mn^rflir rftTiind=r rh=ir rh= ^Trftrifl - if ius = rh = 



Need a customized Linux 
platform? 



p=rnrTi^nn= rr n n .inn: , Firl * =n-^=lFn= 
nav. :ei-torias toti se've' ape ances 
cctoia:e desittus 






i Jir 



I in jm pi =friii"n t=rJin ilr rjy . Win rrii-fi l-ifln a 
dacada o- e -oe rier ?e tui dinq Linu^: sc uticis, 
Mcnenv's LirjK f-OCtl picieeed e ni-Tibe' of tie 
Lyd nulLjiyt drid bo^L jrdi;.iuwt J dL = i=oy Uiu 






Figure 11-5: A corporate Web site with the tables made visible. 



-■ h'MI i i.:IH I H+t-i:J M kl '.fc i>H llH-llihH t.::.|.' Nm+I 



-osa 



rtti Edit Vitw raw<uit£B Tools Help 

a isi ■.;■ , ** € [,-t & s -^ 

i.Ldl puil/l ic^tr L L/PTS.^TB-i niui J. 1 




&■><*! P««t Cm^ii PtmIi AU..I I--,, 



; P I s C I T 1 1 E B A G 



J^pikpn l-^unrh 

13 January. 2004 



Democrats Dcimb Civilians Too: _at'; a cet cfTcur ttic; 
r .c z -r qliVfiijc vvl- t I- ii- - i^ . inr irnh ir thn hirnh ir n~ 
Yjlj^Iuv j^ Hui j jrj j ww UJL .^ Iiuii .. ulu[_ u ul juiuI 
scjices Huiicn Rgl"s Watch suiiiuj-j < 
litirirSri.il 



Fiur HPW ljuiI; 

iff {1 .'.'■ ^'■ffl=*V .SlPyTnr*^' 

"stent released Zeds' 



**P IFrti'ip*)T^ n 






cr tf.s gr^p^s £,^ 5 f ^ f ih -^ i,v5y ^-0^ et.tojc c.'aa^? 1 '.-^ i ^oj/^ 



Figure 11-6: Another popular layout, floating page and multiple columns of content. 



PI: JYS 
WY022-11 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 1 79 



f£] h'l.iin.Jii.ln+tlLiy MkTjs-jli In i Mil 1 1 hkl bh|il-ji«i 
Flh F ■ 1 1 r Wevt FmKtfites ThhiIs H'I|i 

o ■ o i"' =) ft £ n? * © 0,-t^i 



PrfH^ ^]http:^lozahost, , Ch^.:jrlL/P - 3, , =TIi-birc/ 




*,4.W *-.,** b^-J. AW P. 



In rhp i/i hnkrerl 



PUhCH I h t 13 A G 



LS r-ikprl U unr hi 



TRxr^nT^nrn 



Wednesday, A.pri I V, VUULI 

iDemo ciots BoinLi Civilians Tod; Let'; -= II get chr olt re 

|-=ft f r q-it=ni.= whi-ft -inr^=^. F=mFr"iRr Tip -inrrh iq if 

i'uy Jtldv i= 7 Hui =r j- 1 d I yyy t U jiU I ■: un d jul- p j l I hL u ■ ■ 

;o.irres: IH-imai kg -it; Watch SLUTrar 1 ,. ard Amne = ty 

ntenaiiora . 



■i HW1 rj|jul: 

W-'j-w nV yto't, Fc!j'j-tty ". 2000} — /tnjul ?• 
1 .',■> r.irer/ separate .'.t /.-k.""?; 5s s .>=;.. 
tjr.r.'..-- ."'-/ .'.\- |L v-vr." 1 .", /-*/tr'~/t; niy-r. LV.-' 



<.fb '"■es'dar.i if' 1 ! C!ir.*c.-- wz'tf.ej ire i-OMO i:o.-/:a!.--p of 

!ear.z.rg wfjiz is a Y.'-irBS a.? j itstsg'c <j.zeste'-". fn.r.e 
r> i >* , ( a .' 7fi.iy n 1 ^ r.f ffc. I .> > i a rf ^.iTdnrr. {'«<) ra'i, J Tr.'.z ■> ^ | 



! ^j n-rf 



Figure 1 1-7: The floating page and two-column layout with visible tables. 



Floating Page 



The floating page layout (as shown in Figures 11-6 and 11-7) has become quite 
popular and is used in pages of all kinds, from corporate sites to personal Web logs. 
The effect is fairly easy to create using a few nested tables, as shown in the following 
code, the output of which is shown in Figure 11-8. 



OCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 01// Eh 

http://www.w3.org/TR/html4/strict.dtd"> 

ml> 

ad> 

ti 1 1 e> Fl oati ng Table Format</ti tl e> 

style type="text/css"> 
<!-- Sets "desktop" color (behind page) --> 
body { background -col or : #B0C4DE; 1 

/style) 

ead> 

dy> 



< ! - - /Body container - - > 

<!-- (background = border, padding = border width 
margin = centered table) - - > 
(table border="0" eel 1 paddi ng="4px" eel 1 spaci ng="0" 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



80 PartM ♦ HTML/XHTML Authoring Fundamentals 



styl e="background -col or : black; 
margin: auto;"> 



Ctr> 
<tc 



<. ! - - Floating page - - > 

<!-- (padding = page margin) --> 
(table border="0" eel 1 paddi ng="5px" eel 1 spaci ng="0' : 
wi dth="732px" hei ght="900px" 
style="background-color: #FFFFFF;"> 
<tr align="left" va 1 i gn="top"> 
<td> 





<!-- 


Page 


conter 


t - 


> 






<p)Content 


goes 


here 


.< 


P 




<!-- 


Page 


conter 


t - 


> 




</td> 












</t 


r> 












</ta 


ble) 












<!-- 


/Floe 


ting 


page - 


-> 






</td> 














/tr> 














/table> 














!-- /Bo 


dy cor 


t a i n e r - - > 








/body) 














/html) 















I ffi rifratin;! TfibU Tornmt - Microsoft Internet Explorer 



usa 



Fil# F-ilil Vii-w FhvdnIek TddIh HhI|» 



o - o • e el ■ p -t * e 



B 'i 



£dci=sj ^haui/.'luLclliuiL.'CliduL-ill/Fijll-S. 



3Bf 



- 



g] Pans 



^ Lcca htra^at 



Figure 1 1-8: A floating page can add a bit of simple design to your documents. 



PI: JYS 
WY022-11 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 



T 'P Note the comments in the code delimiting the individual tables and content 

areas. It is a good practice to follow standard code formatting (indentation, 
liberal white space, and so on) and add sufficient comments to easily keep 
track of all your tables, how they are formatted, and what they accomplish. 

If you want more of a drop shadow effect, you can play with the borders of the 
floating page, setting two adjacent borders to a nonzero value, as shown in the 
following code: 

< ! - - Floating page - - > 

< ! - - (padding = page margin) - - > 
<table border="0" eel 1 paddi ng="5px" eel 1 spaci ng="0" 
width="7 32px" hei ght="900px" 
style="background-color: #FFFFFF; 
border-right: 4px solid black; 
border -bottom: 4px solid black;") 

This code will visually increase the width of the right and bottom borders, giving the 
page a more realistic, three-dimensional drop shadow effect. 



y 



T 'i' As you read through this chapter, keep in mind that you can combine the 

techniques within the same document. For example, you can put a two-column 
layout on a floating page by nesting a two-column table in the content area 
of the floating page table. Then, within one of the columns, you can evenly 
space out a handful of graphics by nesting another table in the column. The 
possibilities are endless. 



Table Layout versus CSS Layout 



As you'll see in Part II of this book, CSS provides plenty of controls for positioning elements 
in a document. Since CSS is "the wave of the future," why not learn and use CSS instead of 
tables for page layout purposes? 

♦ Most user agents support tables, while CSS support is being slowly adopted. 

♦ Tables are more forgiving when the browser window size changes— morphing their 
content and wrapping to accommodate the changes accordingly. CSS positioning tends 
to be exact and fairly inflexible. 

♦ Tables are much easier to learn and manipulate than CSS rules. 
Of course, each of those arguments can be reversed: 

♦ CSS is pivotal to the future of Web documents and will be supported by most user 
agents. Using it now helps guarantee future compliance. (A lot of table attributes are 
being deprecated for CSS, for example.) 

Continued 



PI: JYS 
WY022-11 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



182 PartM ♦ HTML/XHTML Authoring Fundamentals 



Continued 

♦ CSS is more exact than tables, allowing your document to be viewed as you intended, 
regardless of the browser window. 

♦ Keeping track of nested tables can be a real pain— CSS rules tend to be well organized, 
easily read, and easily changed. 

In short, arguments can be made for both technologies and the debate can get very heated 
(try searching for "html table layout versus CSS layout" at www .google, com). My advice is 
to use whichever technology makes sense to you— use what you know or what presents your 
documents in the best light. 



Odd Graphic and Text Combinations 



Note 



You can also use tables to combine text and graphics in nonstandard layouts. For 
example, look at the header in Figure 11-9. The header graphic is actually several 
pieces, as shown in Figure 11-10. 

The buttons in the page's upper-right are contained in separate table cells for 
a variety of reasons— the most notable is to provide navigation using separate 
elements while still providing a cohesive graphic. 



$) ruiichthfcBnq - Micro soft Interna Ex plorer 



;Ha 



FIU Frill 'Jlnvi Fm/ftfllftS ToftJs Hfil|i 



o - o la^Lp^fe ^^fti a 



Address ^ hrrp:j/nr=ihrrs-,fr. hartfiH 1 j\> I Kjl- 1 K-nnhnrrl/ 



Ba 




Arltn. Pu»cL &«»| EWb Email P.in^ Atnu! I'urcli 



PUMCHTHFBAG 



Spiked Punch 

13 Jaruc.ru, 2004 



we rin parlay, April ? r ?nnrt 

Democrats Bomb Civilians Too: Let's a I gst Dlt our iroral 

stl'-iytUeuji: wif.lt! huri.^. Rdridruer Lib LiuiriLiiriy uf 

YugDGlcMa? Here ere a tew tdbtc t-orn a couple ct locral 

-.i nriiH-.: Hi.m^ri Rikh s Wnli:r siirriri-iry nrnJ Am 

[ntBmatijnal . 

r ron HRW rcpo-:: 



l£ 



J^]>5-|3 



*J .ocal intranet 



Figure 11-9: Presenting graphics and text in a nonstandard format. 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 1 83 



fV, J«r Kaiiri H n|,,-.|, h'ir. .home leti 




ees 


nift F.liT Vie.vj IniFirjfc Fffa.Tts (talnis 1 iiyftra Dbjecfa -".frl*i:liinis 


l/l it? ks Vn i ii 1 1 ow H*l 1 1 




J I] l* U m | € Zi I >fe ft | cs rg | £, h HI HD G 5 Sf7 d 



ft 

Q 




5&J:t 

I s.tuiM 


CO* 
~* ■■-■■ ► 

r l.li 

F 

e ■■ 

El 


■ 



jmaoc: LifJ s lbi s Lii J'.fcKBvtcs 



Figure 1 1-10: The various pieces of the header graphic. 



A table with no padding and no spacing is used to put the pieces back together into a 
complete image while allowing text to flow to the right of the face portion. You can 
see the various pieces and the text in the table layout shown in Figure 11-11. 

Code for this completed header is shown here: 



Cta 



Cta 



- Hea 
ble b 
tr> 
td va 

<img 
wi 
/td> 
td> 

- Nav 
ble b 
tr> 
td wi 
! -- N 
table 
width 

<tr 



ding container - - > 

order="0" eel 1 paddi ng="0" eel 1 spaci ng="0' : 

1 i gn="top"> 

border="0" src="images/home_top . gi f " 
dth="240" heiqht="118"> 



and main gnaphic - - > 
order="0" cellpadding= 



eel 1 spaci ng="0' : 



dth="100% 

a v ban 

bonden=" 
="100%"> 



eel 1 paddi ng="0" eel 1 spaci ng="0" 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



]34 PartM ♦ HTML/XHTML Authoring Fundamentals 



I ^1Jittp:'"l*calho9l-'Clm|:-ler11 PTB PTB-n->hord lituki.litin - Microsoft Internet Exp lore i 



£@5 



Fll* F-lli 'Jlnvi Favorites Tco\S rtelg 

a - a - e e & p ■:> * e 0- & fm 4 



Address ^ hrrp:j/nr=ihrrs-/( tvfTftMl/h'IKjUK-nrihrin-l/hftfldftr.hrrTi 



SHi 




^n L„, ^ ^^H^^H 



PUMCIITIIEBAG 



liAIN CONTENT EIEEJE 



SF.TOMT.' A"R V fiONTF-K" HF.TF. 



g 



Figure 11-11: The completed layout in the table. 



<td width="25%"> 

<a href="archi ve/i ndex . html " onf ocus="thi s . bl ur ( ) " 

onMouseOver=" a rchive.src='i mages/a rchi ve_punch_on . gi f ' 

onMouseOut="archive.src='images/archi ve_punch_of f . gi f ' 

> 

<img name="archi ve" border="0" 

src="i mages/arch i ve_punch_of f . gi f " 

width="132" height="38"X/a> 
</td> 

<td width="25%"> 

<a href="guest/i ndex . html " onf ocus="thi s . bl ur ( ) " 
onMouseOver=" guest. src=' i mages /g_punch_on . gi f ' " 
onMouseOut=" guest. src=' images/g_punch_of f . gi f ' " 
> 
<img name="guest" border="0" 

src="images/g_punch_of f . gi f " width="116" 

height="38"X/a> 
</td> 

<td width="25X"> 

<a href="mailto:email@example.com" 
onfocus="this.blur( )" 

onMouseOver="email . src=' i mages /e_punch_on . gi f ' " 
onMouseOut="email . src=" images/e_punch_of f . gi f ' " 



*J -ocal infranet 



<img name="emai 1 " border="0" 

src="images/e_punch_of f . gi f " width="113" 

height="38"X/a> 
</td> 
<td width="25X"> 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 1 85 



<a href="about/i ndex . html " onf ocus="thi s . bl ur ( ) " 
onMouseOver=" about. src=' images/a_punch_on . gi f ' " 
onMouseOut=" about. src=' images/a_punch_of f . gi f ' " 
> 

<img name="about" border="0" 
s rc="i mages /a_punch_off . gi f " wi dth="131" 
height="38"X/a> 
</td> 
</tr> 
</table> 

<!-- /Nav bar --> 
</td> 
</tr> 
<tr> 

<td width="100%"Ximg border="0" 
src="images/home_flag . gi f " hei ght="80"> 
</td> 
</tr> 
</table> 

<!-- /Nav and main graphic --> 
</td> 
</tr> 
<tr> 

<td height="158" val i gn="top"Ximg border="0" 
src="images/home_l eft . gi f " wi dth="239" 
height="156"> 
<p>SEC0NDARY CONTENT HERE</p> 
</td> 
<td val i gn="top"> 

<p>MAIN CONTENT HERE</p> 
</td> 
</tr> 
</table> 
< ! - - /Heading container - - > 

Using this technique you can wrap text and graphics around each other in a variety 
of ways. For example, if the graphic used in the preceding example descended on the 
right as well, you could use three columns — pieces of the graphic in the first and 
third, text in the middle. 



Navigational Menus and Blocks 



The completed page header shown in Figure 11-11 has its navigational elements in a 
row at the top of the page. You can construct similar, vertical layouts for your 
navigational elements using rows pan attributes in your tables. For example, 
consider the following code and the output in Figure 11-12. 



(table border="l" width="100%"; 
<tr> 

<td rowspan="4" width="65Z' 
<p>Header graph i c < / p > 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



186 PartM ♦ HTML/XHTML Authoring Fundamentals 



</td> 
<td> 

<p>Nav_K/p) 

</td> 
</tr> 
<tr> 
<td> 

<p>Nav_2</p> 
</td> 
</tr> 
<tr> 
<td> 

<p>Nav_3</p> 
</td> 
</tr> 
<tr> 
<td> 

<p>Nav_4</p> 
</td> 
</tr> 
:/table> 



^J http://localhost'Chapter11/Fig11-12.htni - Microsoft Internet Explorer 






ESS 


File Edit View Favorites Tools Help 








♦ 


OH. O - B B tt | P ? • • |a* ift ■ * 










Address 


S http : //localhost/Chapter 1 1 /Fig 1 1 - 1 2 , htm 




H £ Go 












a i 




Head 


Nav_l 










Nav_2 








|Nav_3 








|Nav_4 






















J] Done 


fc jL 


ocal intranet 







Figure 11-12: Using rows pan, you can create vertically stacked elements. 



Note 



As you have no doubt realized, there are multiple ways to accomplish many of 
the designs shown in this chapter. For example, you could have just as easily 
nested a one-column table in a cell instead of using rows pan in the example 
code shown for Figure 1 1-12. The point is that tables are very flexible and can 
be used in a variety of ways to accomplish the desired layout. 



PI: JYS 

WY022-11 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



Chapter 1 1 ♦ Page Layout with Tables 1 87 



Multiple Columns 



As covered in Chapter 10, you can use tables to position elements in columns. This 
technique can be used for a variety of layout purposes: 

♦ Providing navigation bars to the right or left of text (see Figures 11-4 and 11-6) 

♦ Putting text into columns (see Figure 11-4) 

♦ More precise positioning controls, putting text next to graphics, and so on 

Columnar formatting is simple to accomplish, as shown in the following code: 

<table border="l" eel 1 spaci ng="0" eel 1 paddi ng="5px" 
width="100%"> 
<col group> 

<col width="50r'> 

<col width="50r'> 
</col group) 

<tr> 

<td col span="2">Header graphic or navigation can go here</td> 
</tr> 
<tr> 

<td>First column content ... </td> 

<td>Second column content ... </td> 
</tr> 
</table> 

The output of this code is shown in Figure 11-13. 



] Multiple Column Format - Microsoft Internet Explorer 



B@B 



File Edit View Favorites Tools Help 



g-q-b m ■£ , p &*«a~&H4 



Address 



| http : //localhost/Chapter 1 1 /Fig 1 1 - 1 3 . htm 



II 



BB< 



Header graphic or navigation can go here 



First column content. 



Second column content. 



*j Local intranet 



Figure 1 1-13: A simple two-column format. 



PI: JYS 
WY022-11 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:1 



188 PartM ♦ HTML/XHTML Authoring Fundamentals 



Note 



One caveat to creating columns with tables is that the content doesn't auto- 
matically wrap from one column to the next (like in a newspaper). You must 
split the text between the columns manually. 



Of course, the columns do not have to be the same size nor proportional to each 
other. You can define the columns in any size you need by using the appropriate 
formatting attributes. For example, if you wanted a navigation column to the left that 
is 200 pixels wide and a text column to the right that is 400 pixels wide, you could 
use this column definition: 

<col group) 

<col width="200px"> 

<col width="400px"> 
</col group> 



Summary 



This chapter showed you how to use tables to create various page layouts. You 
learned that tables, employing techniques from rudimentary formatting to graphic 
and text combinations, multiple columns, and navigational tools, can be used as a 
powerful and flexible layout tool. You will learn about more ways to format 
documents — using CSS — in Part II. 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



Frames 



c 

^^ everal years ago, almost every document on the Web 
^^ contained frames. The frameset structure provided an 
easy way to create multiple, separate scrolling areas in a user 
agent window and a flexible mechanism to modify the content 
of frames. 

However, frames have turned out to be more of a fad. You can 
have many of the benefits realized by using frames by using 
the infinitely more flexible and powerful CSS formatting 
methods. 

That said, frames still have their uses and have even spawned 
their own official Document Type Definitions (DTDs) to handle 
their special tags and needs. This chapter introduces the 
concept of frames and shows you how to add them to your 
documents. 



Frames Overview 



At their simplest level, frames provide multiple separately 
scrollable areas within one user window. Many non-Web 
applications use the concept of separate panes to help their 
organization and controls. For example, Figure 12-1 shows the 
Windows Explorer, using a left pane to display folders and the 
right pane to display files within the selected folder. 

As you have no doubt noticed, the different panes in 
applications such as Windows Explorer can be manipulated 
separately from other panes. The same is true for documents 
utilizing frames. 

For example, take a look at Figures 12-2 and 12-3. They show 
the same document except that the window in Figure 12-3 has 
been scrolled to view the bottom of the text in the document. 
This has caused the navigation bar to scroll as well, in this 
case almost off the screen, where it can no longer be 
immediately accessed. 




♦ ♦ ♦ ♦ 
In This Chapter 

Frames Overview 

Framesets and Frame 
Documents 

Targeting Links to Frames 

Nested Framesets 

Inline Frames 

♦ ♦ ♦ ♦ 




189 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



■ A|fiiclie2 



File Edit View Favorites Tools Hel|] 
Q Back r. ( • tJ \p leatch {3 FoUers | T3i T 



E(5]g 



Address |p^i filPrnnncn Files'.Apcche Grojp\Apache2 



BB< 



Folders 



lr 



Li, 



L^ Local Disk (C;) 
■f (q Doiumsntc and Settir. 
Fl (q PrngrflTi Filp^ 
l£| Apache Group 
B O Apache? 
El (£|bin 
If^i cgi-bin 
f"li conf 
Ir^i Cuuy u" 
Gfcl li^i crrsr 
l+] |r^( htrnr*; 
S Ic3l icons 
Ir^ include 
|£|lib 
Ologs 
■+■ l£3 manual 
li'^i module: 
(r^t prcxy 
QH |£) Conmcn Fies 

P 3 ! CotiPIls Applicati 
S Cl InstallEhield Instc 
S Q Internet Explorer 
S llj^l Jasc Software '.rv. 

d Messenger 
iii O microsoft frontpa 
CD (Si Movie Maker r — i 

m p, „„ i „, Ci .„ ti . J el 
I M 



3 •*» 

~J Copy off 



LiANbtb 
Text Document 
589 K3 

L]CEI\5E 
Text Document 
25 KB 



htdo. 



logs 



,;bout_apache 

Text Docjmcnt 
15 KB 

1Mb I o,LL 

Text Docjment 

HKB 

README 
Text Docjment 
HKB 



Figure 12-1: Applications such as Windows Explorer use multiple panes to display a variety 
of information and controls. 



I qjj Home - Microsoft Internet Explorer 



File Edit View Favorites Took Hol|j 

o - o - s s & I p & * a I p - ^ m -% 



Adcicss |i^lLuJ://lu-jllu^,'did|J.t;r:£/FiyO:iiui/ 



~BB- 




Corporate Site 



J 




Loretr. ipsurn dolor sit soie;, con.se ctc-tuc-r adipiEcmg eh:, sad diam nor.umrny nibh eui;mod 
tir.cidun: ut laoreat dobre magna aliqucrn arat volutpa:. Ut wisi c-rum ad mimrr. veniam, cms 
nostrud CKcm tatbn jllErncorpcr suscipi: loborts nisi at sliquip ck ca ccmraod* nonscquat. 
I>jjs autcn: tcI coin mure dolcr m lier.drerit in vulputate velit esse Lr.olcs^c ; onse ^uat. vel jHu.ii 

dobre e u feugiat r.ulla fkcilisis a: vero eros et £ccums£n etiusto odio tignissim qrjitlar.dit 
praesertflipTimimznildelenit augue duis dobre t5 feugait nulla facilisi. Ut wis; eritn ad minim 
venizrn, cnis nf?s:r.id e:^erci tatior. uLarr.coqoc-r s.iscipit lo mortis msl nt sJiqiii-s ex ea commode 
cor.saquat. Dui; autemvel aum inure dslor ir. hc-ndrc-rit it. vulputate veht esse molestic- 
cor.caquat, vel Jtam colore eu feugict nulla fanilisis at vero ercc et ancurrj.ca.-i et lucto odio 
digjiissitn qui blandit pracscnt lup:£.tum zzrH dclctiit auguc duis dolorc t^ fcugajt nulla facusi. 
Loicci. lpiuiJi 'JfS.'Ji siL Mine, uyiiKtuLtLuti tidiTjituuj^ cli,, s^d dam ]i"i.uiijnv iiibli cuiiuud 
tkeddun: utlaorest dobre magna aliqu£m srat volutpa:. Duis autemvel eum ir.ure dobr ai 
hendrer.tir. vulputate veit esse rnolestie c or.se qu£t r vel ilium debre eu feugiat nulb fa;ilisis at 
ver^i eros et acrnmsan etivs:c odiii dignissim qi.iiH^ridLtp<raesantli.iptati.i^iiznl deleot ancr.ie 



j,.j. ri-.u.^r +^ f-.„^ m ;4.„.,u f^^I 






- 



a,t 



\J Local r 



Figure 12-2: A long document uses scroll bars to allow the user to see the entire document. 



190 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



Chapter 12 ♦ Frames 



1 0] Howe - Microsoft Internet Explorer 



BUS 




Favorites Took Hol|i 



uiL,'did|jLer:Z/FiyO:ii0£/ 



EB' 



I>jjs auterr. vel earn inure dolcr in iaer.drent in _ .7ulputate velit esse rr.oles:ie nonsequat. vel illu.-n 
dotarc cu fcugikt nulla :£.cilisis a: vcro cro; ct cecums zn etiusto odio cigmssmi quiblar.dit 
pracsent Aip:2.tuo zznl dc^ctiit auguc duis dolorc t; feugait nulla fatilisi. Ut w.s. criin ad r.iiiiiin 
v matin, c uls no s i jd cj-ici ui lalioi. ulaii.uo: p ti s js upil lob -ji lis nisi uL tJiiq utj ex ea. uociujio do 
cor.s squat. Duis autemvel sun inure d^lor Lr. hendreritir. vUputate velit esse molestit 
nars^quat, vel llirn colore eiifeii£i£tnilla fa^ilisis at vera p.tcs et a^nimsai eh -listo fidio 
digni^un qin blandit praesent j.ip:?.tum zznl delenit augie dins dolore t? teugait nulla tactisi. 
Lorerr. ip:um dolor sit ame: ? consectetuer adipiccmg eli: ? c^d diam nor.urr.my nibh euiimad 
tir.cidun: utlaorcut dolore magna aliqusni urat volutpa:. Duis autemvel cum ir.urc dotar m 
liendrer.t 11: vulputate velit esse molestie tw.se quat, vel ilium dclore eu feugiat nulla fai-ilisis at 
?en> eros et ac;unsan etius:c odb di£nissim quibl^ditpraessntluptatimzzri deler.it augae 
duis dolore te ftugait nulla facilisi. I-oretr. ipsun dolor sit a.ne: r consectetuer adipiscing tli: r 
sed diarn no-iiirrirri^nihh euisrnod tirnio.nnt ut I afreet do I ore rna^na aliquarn =rah irohtpa: TTt 
w.sl enim adrnimm ^eoam, qui£ nostrud e^erd tation jJlsmcorper suseipi: loborts nisi ut 
aliqitp eis ea commodo concequat 

Loieu. lpiuiJi doloi sit a:iic,, uoiistuLtLuti tidifjit uu^ eli, ? s^d diam noi.uiiiiiy mbh euiinud 
tir.cidun: ut laorest dolore magna aliqusni srat vokitpa:. Ut wisi erin ad mtnirr. verdant, cuis 
nostrud exerci tation jUsmcorper suscipi: loborts risl "it aliquip ex ea ccrnnodo ;onsequat. 
D.iis auterr. vel e.im inure dolcr in .aer.drerit in -julputate velit esse tr.ole:s:ie :onsequat. vel iUiina 
dobre eu feugiat r.ulla :£cllisis a: vero eros et accumssn etiusto o-dio cignissim quiblar.dit 
praesent ^iip:ctum zsril de^etiit aug';i3 diac dolore t2 feugait nula facuci. Ut w.c: eom ad minim 
Tcmsni, cms ncsxad cxcrci tatior. ulatr.corp'Cr sasapit lobortis msl ut aliquip ck ca commode 
ut'LijiquaL. Duii aulcni vtd iuomue d^loc u. htndctiiLu. vidpL-Lalc vcHtcsic iiio^csLit 



> 



- 



g|pon3 



x J Local ntranet 



Figure 12-3: When the document is scrolled, the entire view— including the navigation bar 
on the left— is moved. 



Now take a look at Figure 12-4. Each element — the top banner, the navigation bar, and 
the main content — has been placed in a separate frame. When the main content is 
scrolled, the banner and the navigation menu remain static within their own regions. 



Framesets and Frame Documents 

Frames are a bit complex to implement, as they require a separate document to 
define the frame layout as well as individual documents to actually occupy the 
frames. This section takes you through the pieces of the defining document, the 
frameset, and shows you how to create a frame-based layout. 



Creating a frameset 



A frameset is created like any other HTML document except that its content is 
limited to frame-related tags. The following skeletal document is an example of a 
frameset document: 



C ! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset// El\ 

"http : //www. w3.org/TR/html4/frameset.dtd"> 
Chtrnl) 
;head> 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



192 PartM ♦ HTML/XHTML Authoring Fundamentals 



/&] Home - Microsoft Internet Explorer 






sua 






File Edit View Favoiites Took Help 

O - O • E tf> P >? * « 


P- 


* m ■* 


.:■• 



Adcicss |ffi | Hp:/Ju_dll mL.'d id^Ler 1 g/FiyO-t/ 



^H< 




Corporate Site 




ij£|Don3 



diis do ore tF feigsit nulla Fsnilisi T^j-fhi irsiin color sit aniFt, ronsFrtptiiFr adpisr.ing Flit, 
sed diam ncnumir.y tubh emsmod Tincidvnt Lit lzuiree; dehre magr.a sJiquao ei^.tv^Litpat. Lit 
wi£i en™ ad minLO veniam. qui; nostnid e^era tstionullaocorper susmitlobortis nislut 
aiquip ck na nommod;> conscquat. 

L/j:tin ipsjm dyk'i at ameL, l^usclLcLjci aupismik eliL, sed uani [I'jnuimr/ [jibli euiojud 
tincidunt u: lasree: dolore magna aliquan eratvoxupat. lit ^.si enim adminm verian, quis 
nostnid F^p-ri tstim ullanr.firr>=r susr.nit lob-ortis nisi lit }tinlrp Fy Fa roimnodo nmspquat 
L'lils intern vel eLim ltr.ire dclor nhendrent n v.ilpjtate veli: esse molestie consequat, vel ilium 
dslore. eu ieugiat nulla facilcic £t vero ers; et ac cuius an et lunto odo dignissm qui blandit 
pi^cscr-tluptat-imzEril ddcnit auguc duis dolorc tc fcugait nulla faciisi. TJt _ ^ia snuu ac mjiim 
yemaiu, quis nustrud ex^rci tatisn ullamccrper suscipit ^bo/ts nd ut aljqu.p ex ea commode 
U'jiisequaL Duly aultni vel ejmniuie duk'i in jiei.di cut in ^ulpuliilc vclil esse [i.ulesUe 
conseqnat. vel ilium dolore eu fengiat mila facJisi; a: vers eros et ac;nnsanetius:o odb 

* J Local ntranet 



- 



- 



Figure 12-4: Frames allow one region to scroll while others remain static. 



</head> 

<frameset attri butes> 

<frame attr ibutesX/f rame> 
<frame attributesX/f rame> 

</f rameset) 
</html> 

Note the following about this code: 

♦ The document uses the frameset DTD. The frameset DTD is essentially the 
same as the transitional DTD except for the addition of the frame-specific tags 
(and replacement of the <body > tag, covered shortly). 

♦ There is no < b o dy > element. Instead, the <frameset> tag provides the next 
level container under <html >. 

4- The <f rame> tags, nestled inside the <f rameset> tag, define the content for 
the frames and various properties of the frame itself. 

4- Other than the <frameset> and < h e a d > sections, there is no other content in 
the document. 



The basics of the <frameset> and <f rame> tags are covered in the next two 
sections. 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



Chapter 12 ♦ Frames 1 93 



The <frameset> tag 

The <frameset> tag defines the layout of the frames in the document. It does so by 
specifying whether the frames should be laid out in columns or rows and what each 
column's width should be. 

The <frameset> tag has the following format: 

<frameset cols|rows = "col umn_or_row_si ze (s )"> 

The column or row sizes can be specified as percentages of the user agent window, 
pixels, or an asterisk (*), which allows the user agent to assign the size. In the last 
case, the user agent will typically split the remaining space across the columns or 
rows that specify * as their width. In any case, the resulting frameset will occupy the 
entire user agent window. The number of entries of the cols or rows attribute also 
define how many frames will be used — each entry needs a corresponding <f rame> 
tag within the <f ramesetX 

For example, consider these definitions: 

<!-- Two columns, 25% of the window, the othen 

7 5% of the window --> 
<frameset cols = "25%, 7 5%"> 

<!-- Two columns, 25% of the window, the othen 

75% of the window --> 
<fnameset cols = "25%, *"> 

<!-- Thnee nows, the finst 50% of the window, the other 

two 25% of the window each --> 
<frameset rows = "50%, *, *"> 



Note 



<!-- Two rows, the first 100 pixels high, the second is the 

size of the remaining window space --> 
(frameset rows = "lOOpx, 200px"> 



In the last <frameset> example, the second row is defined at 200px. However, 
if the user agent's window is larger than 300 pixels high (the total of the rows 
defined), the second row will be expanded to fill the space. 

The<frame>tag 

While the <frameset> tag is responsible for defining the layout of the entire page 
(in terms of number of frames and their size), the < f r a m e > tag is responsible for 
defining properties of each frame. 

The <f rame> tag has the following, minimal syntax: 

<frame name=" name_of_frame" src="url_of_content"X/f name) 

The name attribute gives the frame a unique name that can be referenced by URLs, 
scripts, and so on to control the frame's contents. The s re attribute is used to 
specify the URL of the content that the frame should display. 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



194 PartM ♦ HTML/XHTML Authoring Fundamentals 



Using only these two attributes results in a frame with minimal margins, no borders, 
and automatic scroll bars. More information on controlling these attributes of the 
frame is covered in the next few sections. 



Frame margins, borders, and scroll bars 

The <f rame> tag supports the additional attributes shown in Table 12-1. 



Table 12-1 
The <frame> Tag's Attributes 



Attribute 

frameborder 



Value(s) 

= no border 
(default) 

1 = border 



Use 



Whether the frame has a border or not 



longdesc 


url 


A URL of a document to use as a long 
description for the frame. (Note that this 
is largely unsupported by user agents) 


marginheight 


pixels 


Sets the top and bottom margins for the 
frame— the distance the frame's content 
is from its border 


marginwidth 


pixels 


Sets the left and right margins for the 
frame— the distance the frame's content 
is from its border 


scrolling 


yes no auto 


Controls whether the frame displays 




(default) 


scroll bars to help scroll the content 
displayed in the frame 



As mentioned in Table 12-1, the 1 ongdesc attribute is not fully supported by most 
user agents. Use it if you need to specify a long description, but don't count on its 
functionality. 

The margin attributes, ma rgi nhei ght and ma rgi nwi dth, are self-explanatory, 
controlling the inside margin of the frame. They should be used to provide enough 
white space around the frame's content to help make the content clear. 



Tip 



When using images in a frame, consider setting the margins to zero so the 
graphic fills the frame entirely without superfluous white space. 



The frameborder attribute controls whether the bounding border of the frame is 
visible or not. Figure 12-5 shows a frameset without borders, and Figure 12-6 shows 
the same frameset with borders. 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



I t&i Howe - Microsoft Internet Explorer 



g I a 



File Edit Viow Fflvoiitos Took Help 



:;; I LI+j ://lu_dll uiL.'d id|J.er :Z/Fiy05/ 



^H< 




Corporate Site 




Lorcm Lpsom color at amct, ccnscctctacr acipiscing clit, scd ciam nonummy nibla cuismod 
tincidunt u: la^ree: dob.~e magna aliqaao erat vojjtpat. lit tv.sl emm admuim "irenao, qui; 
ciosLiud tiidiLi Lt.lio:i ullai:iu oi ;j ii s us ltjiL kb 01 lis nisi ul ilicuip a: ea u uimiio do u ^zis equal. 

Luis autem vd eim iriore dclor h hsndrsrit h vulp atate veli: esse mole stie ccasequat, ^el ilium 
drjlore eu -pii^iat milla faril-s-s ?.tv=-.rc> err^ et a mums an etiu?tr> odd digrmsin qui bandit 
prseser.tluptatjm^sril dele-nit augue- duis dolore te tsugait nulla lacilisi. Ut ;visi snim ac mmim 
tfemam, quis noctrud eiisrcL tatbn ulcmccrper cu3cipit ^obortc nd ut aliquip ei: ea commode 
conscquat Duis autcm ycl cam inure dolor in iacr.drcnt in milputatc vclit esse tr.olcstic 
conscquat. ycI jUllii dobre eu feugiat inula faclisis a: yci^ erg* ct an " urns an ctius:o ^dii 

■Ignis sirn qui frandit praeser.t luptaum mil delenit augue duis dobre te ftugait nulla facilisi. 
Lccem psjm color sit amet r ccnsect.et.ier acipiscin£ elit r sed ciam nonummy nibti euisinod 
tinnidunt in la^ree: dolo-F rn^gna aliqian erat voulpst TJni^ aite-n vel =urn iriure do orir 
hencrent in ™butate velit esse mole stie csnsequat. Yel ilurr. dobre eu fejgiat r.ulla Escilisis a: 



- 



- 



• J Local ntranet 



Figure 12-5: Without borders, the frame divisions are hard to distinguish, which may lend 
well to a seamless page design. 



I ffgj Nome - Microsoft Internet Explorer 



sua 



File Edit View FoynrifOB Tools Help 

a - a - a S ft I ^ * W • I B - £ J^ -a 



;;. I LLp;//lu.dll uiL.'d id|J.er :Z/Fiy06/ 



^H< 





Corporate Site 



Lorsmipsum dobr -Az arnet, :onse;te:uer adip:s;iiig eit sec diam r.orrjmrr.y ribh euismod 
tnniduntut laoreet colore magna ahqua-r erat volutp^t Ot wisi entrn ad rririirn vfnia-n, qiis 
r.ostrud s^erm tatior. uUamcsiper suscLpit bborti; ms^ ut sdiquio ck ea conrjnoco consequat. 
Duis autemvel eum inure dolor in hendrerit in \qilputat3 vslit esse msle:tie concequat, vel iLlum 
dclorc cu fcugi£.t njHs. fanilisis at vcro cros ct an cum; an ct :usto odio digri-SSL-n quiblandit 
piicsc:il lupLti.uiiL ^zii dcliiul au^iu^ duis coloii Lc ."bu^ail mlla TaLiLs:. Ut v/iii anil adiiuuuu 
venia_-n, quisnostrud ei:ercitaticnullam;orper suscipit lob oris nislut adquip ex ea comrr.odo 
consecua:. Duis auternvel eum lire dobr in hendreii: in vaputate "jelit e^e nobste 

c cm? e cua:, veJ Llurn do.f^re =n fengia: nulJa facilisis at ver.? eros e: ac ci.iar.3 an =t i.isto odic 
digrissin qui blar.dit praesent luptaoirn zsril debnit augu2 duis colors te feugait nulla facils:. 
Lorsmipsum dobr 31: amet, :once^teoier a'iip:c^itig eit, 3ec ■iiam r.onjmrr.y obh euismod 
fcncidunt ut lacrcct color; magna aiqua.-r. crat volutpat. Duis autcm vci curr. inure dolor n 
l.ecidieci, 11 wiyuULe vebt cite hi-jIcsLlc uciJHcqua,, vc^ illui:i dolci c eu feudal. :iullci fiuiEsis l±L 



* 



Vj Local ntranet 



Figure 12-6: Frame borders can help your users understand the layout of your document 
and where the frame borders are so they can better manipulate them. 



195 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



196 PartM ♦ HTML/XHTML Authoring Fundamentals 



The scrolling attribute controls whether the frame will display scroll bars or not. 
The default setting, auto, allows the user agent to decide — if the frame contains too 
much content to be displayed, the user agent will add scroll bars. If the content fits 
within the frame, the user agent will not display scroll bars. Use the scrol 1 ing 
attribute accordingly — if you want scrollbars all the time, or don't want scrollbars no 
matter how the frame's content displays. 

Permitting or prohibiting user modifications 

The <f rame> tag also has anoresize attribute that, when set, will not allow a user 
to modify the size of the frame. The default is to allow the user to resize the frame. 

To resize a frame, the user positions the pointer over the frame division and drags 
the border. Figures 12-7 and 12-8 show the left frame being enlarged — as a 
consequence, the right frame shrinks to compensate. 



Double-headed 
arrow 



I y Homo- Mk.osc.ftli.tor, st Explore, 



HI* Edit View rev 



Slubs! |j§http,70C3h35tfCtl. 




Efil 



rites Tenia Hel|> 

! p * # © a * & 



~HH' 




Loretn ipeum dslor cit arnet. ccr.ee ct3:uer adipicang elt. ced diam nonumrr.y mbh eui:ir.od 
fcr.cidunt ut laoreet dolcre ir.sgna aliqusra erst voJutoat. Ut msi enra ad raiitbi veriam, quis 
r.G£tnid ezerci tation LiUarncorp?: - siiscipit tobcrtis nisi Lit siquio e:-i ea ccrarnodo c^nseqiis.t 
Djii ijLeiu <si. cumin jig doki hj :iz::iJi z:::L m vubutale vcliL esse ]i.«L'Icsji u unequal, ,j^_ lLljli 
dulcre eufrugiat njla feucilisis stvero eros et a:.:.jmsan etn;to cdio dignisjir.i qui Kaiidit 
pracscr.t hotatutn zmi. duxru: au^uc dms cobm tc icugai: nulla 1e.cij.3j. U: vns cnur. ad irj--xra 
veriarft, qji£ nsstrud &:erritatbiaullair.corper suscipit Lotortis risl ut aliquip ex ea ce-mmo-d* 
consequat. Duis avt^mvel evrairiire d^Lor in bendrer.t in vulputate veLt esse molestie 
r on s squat, vel ilium dokre mifciipiat ni'la fani1i?is ?.tvf.ro ftds et g-^iimsan Ft r 1^:0 f'dio 
di^iitaji. iiw blii Jil p:acsc]il lu-pLtLjin ij^i ctliiLL. augue duis d^oit Lc rej.J:iiL nulla fiijJia. 
Lorctn ipsum dslor s:t arnct, ccr.se ctn:ucr ackpiscing cLt, scd dam nonumrr.y mbh cusir.od 
fcr.cidunt ut laoreet dolcre ir.tgna aliqucra erct voiutoat. L'uic auteo vel euir. mure dctor. in 
r.er.drerit in vo.puts.t2 velit esse me-lesfce ccr.sequat, velLUm dolc-rs eu feudist nulla fa^Jisls at 



v 



£ 



Figure 12-7: To resize a frame, the user positions the pointer over the frame border 
until a double arrow cursor appears. 



Targeting Links to Frames 



To change a frame's content, you must be able to target a frame. To do so, you must 
use the name attribute to uniquely identify your frames. You can then use those 
names in scripts and anchor tags to direct new content to the frame. 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



Chapter 12 ♦ Frames 1 97 



Drag border to new position 



i : " lli>iiit - M iti osfrft I nte I net C* » I a I e I 



File Edit Viaw Favorites 

o o s @ ^ I ^ 



Address © httDij/ccdhoit^ChaDici It. 




UaiES 



Tools Hel|i 

■it- m « 



&~ a* m ■% 




IB' 



lorerr. ip:jm dolor sit amet, cor.cecteftier adijoiscin^ ei: ? :2c cism n^nummy ribb suismod 
tmiidur.t u: laorcct dolcrc masr.a siquam crat volutpat. UtwisL cnim ad nunim vcmatr., qms 
no-stud ;kcici tetion uUaocorpe." susupitbbo.lis n.;lut aliqujp cj: =a conur.odo con^cuat. 
!■ ins -iul.-:rii vt: i-:i _tt iti it-: i1c:1:jt tt Ht-ncl" i-:"il. in n'i .1: 11 .IhI.-: v-:lil. r.-izr. tt k i1i-:kI: r. 1 o - i:-;r-:r [im ., i^i— :1 ll irn 
elclcure ?li feugiat nulla foetid at vera eras e: s.cc.itnsan ?ti.isto c*cic* dignissim qtri bfendit 
praesent Iup:atutr. zzril delenit augue dui£ colore te feugait nulla facitsi. Ut wisi enim ad miri-n 
v2ria.11. cuis noctruc HEerci tation ■jUamcorper cuscipitlcb orris mdut aliquip ex ea commodo 
cor.scqjat Dms au:cmvcl cjmir.urc dolor in hendren: in vu.pu:atc vclit ussc molc3:ic 
car.secrjat. vclilkir. colore cu frugiat nulla fkcilisis at vcrc ere; ct ati-unsar. et juste cdio 
■ liyrri-MTi qir f:1-iri(hl. p-a-iKi-^ 1. 1i.pLHli.Tri ■'y."i1 dt: ml. a jyi.r: (Iiiik :]o1cti- \r. fi-iujml -lull* fa :i1imi 
lorerr. ip; - .im dolor sit amet, cofr.cectetier adijoiscing eli: ? ;?c ciam nommmy nibb ?i.rismod 
loiidur.t u: laoreet dolcre maor.a slquarn erat uolutpat. Luis ajtemvel sum inure dolor in 
h^ndreri: in vu.pu:a:e veJit esse mole:::ie ncnsequat.. ve. ilium do.ore eu feugiat nib faciei: at 



- 



m 



i Lol-eI intranet 



Figure 12-8: Dragging the curser resizes the frames accordingly. 



Scripting languages can use the document's frame collection to target a frame. For 
example, JavaScript can reference the content of a frame named news by changing 
the value of the following property: 

parent. news. location. href 

You can use similar methods and properties to otherwise manipulate the frame 
content and properties. 




For more information on JavaScript and how it can be used to affect the prop- 
erties of a document, see Chapters 25 through 27. 



When you use the frameset DTD, the anchor tag (<a>) supports the ta rget 
attribute, which can be used to target a frame for content. The target attribute 
supports the various values shown in Table 12-2. 



Note 



To understand the difference between the _parent and _top values of the 
target attribute, you need to understand nested frames. Nested frames are 
covered in the next section. 



The easiest way to direct content to a frame is to use the frame's name in the 
target attribute of an anchor. This technique is often used to control one frame 
independently from another, especially where one frame has a navigation control 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



198 PartM ♦ HTML/XHTML Authoring Fundamentals 





Table 12-2 
Possible Values for the Target Attribute 


Value 


Use 


framejiame 


Displays the content in the frame specified by frame_name 


blank 


Open a new window to display the content 


_parent 


Displays the content in the parent frameset of the current frame 


self 


Displays the content in the current frame 


_top 


Displays the content in the current window, without frames 



and the other displays variable content. For example, the following code provides a 
handful of navigation links in the left (na v) frame, and the content is displayed in the 
right (content) frame. Figure 12-9 shows what this code looks like in a browser. 
(Only home.html is shown in the following code — other content pages would look 
similar.) 



■:: 



Simple H\i 



: N.-wiq.-^n ■ Micr.^R Internet E«|,| i: . ro r 



yjgy 



rile E<lit View rewrites Toe la Hel|> 

a - o 3 ia ft p * * & j a - 1* m -a 



£Li_re>i |iQ http : .7 a:3hD;t/chapter . :/= oosffraneset. htTl 



ProU;-.; 



"HH< 



Acme Home Page 



Lwemjpsur.i do^or sit ainet. Lonsectetuer adipiscmg clit. 3;d dao ncu'-uuriy .ibh cuismcdtii:cid"Jiitutlair;;t 
colars ma^r.t ali^ijam eratvokitpat. Jt wisi enim admxirn veniair., quic no:truc 35cer^: :auon ulcrnccrper 
susnipitlcocrtis nisi Lit sJicuio e:-: ea coinmoda cons squat. Buis autemvel eum inure cotar in hend.-eri: in 
vulp.i:ate vedT ?s;e rnolestie consequaT, vel ilium dolcre eii feuoiat n.ida fecilUi; z.tvero er^s eT ar rums an et 
nislx: :j(liu di^-rnKKrri r:i.i bli-intiiL [ jt -ii-:m -r il. 1 ii] i .h Ij jt i i y.yrl dutanl jyr diM ilolo't: l.n Pi-ii^jjhiI "i il-i H-iuIim 

Ut vrisi emm ad minim vcniam, ^lus nostrud c;-:crci tiosn ularr.corpcr s'jscipi: lobars nisi x aliquip ex ca 
ccmrnodo csneequtt Duis auternvel earn inure color in hend-en: in vulpjtate -juaz ecc2 tnclestie consequa:, 
veliHuir. dolore eu feugiat nulls facilisis a: vers eros et accutnsan e: iusto odio digpUstii quiblandit ora2;en: 
luptaTjirn 77r1 dfileniT auri= duis dnlorfi tp. fhiigait ni'la faniliid T.drFn ipsiun dolc.r sit sn=::, nr>ns=":i:ftTi.:Fr 
MupLtLiiiJ elil* sec dan. iiLJULiiJiiiLi 1 mbli euaioLod linuidu-L ul jacietL d'j-l-L'it magna tJiquanj eial vjlu.lf:t.L 

Duis au:etnvel 2am inure dolor in hendrent in vulputate "J3li: ecc2 incline conseqaa:, vel Hum dolore 2J 
feugis.t nulla facJisis atverc 3ro; et accurr.ssr. stiustc scio digrissirn qui blandi: praesent lup:atum zzril delenit 
angle duis catair? te feugair nulla facilisi. Loretr. ipsurn d:ilor sit atr.et. ccr.cectetuer ac'ipiscing eLt, sec diarn 
ncrurnmyrnh fiiiismrd timdimT n: laorp.p.T dolors magi^ aliquarr pra: ^rolntf ■ at TTl: wsi Frirr ad rnhrn 
veman: r quis nos _ j"ud ckci^l tatic.iullainccrp cr suscipit lobc.lis nislut aliqjip c^ ;a c^.T.uucd^ conscquat. 



^j http /r|ocolho:t;chcptctl2rFig00ihDin=.htTl 



*J Locol ir 



Figure 12-9: A simple frame-based navigation scheme. When the user clicks a link in 
the left frame, the content changes in the right frame. 



frameset. html 

< i DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Fraineset//EK 
"http : //www. w3.org/TR/html4/fraineset.dtd"> 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



Chapter 12 ♦ Frames 1 99 



Chtml> 
;head> 

<title>Simple Frame Navigation</title> 
;/head> 
<frameset cols = "20%,*"> 

<frame name="nav" src="navi gat i on . html ' 
<frame name="content" src="home . html ">• 
</f rameset) 
;/html> 



></f rame> 
/f rame> 



navi gati on . html 



DOCTYP 
"ht 
tml> 
ead> 
<title 
head) 
ody> 

<P> 
href= 
href= 
href= 
href= 
</p> 
body) 
html) 



E HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset/m 
tp : //www. w3.org/TR/html4/frameset.dtd"> 



Navigation Menu</title) 



home, html" target=" content ">Home</aXbr> 
"products, html" target=" content ">Products</aXbr> 
"contact.html" target=" content ">Contact</aXbr> 

a bout. html" target=" content ">About</a> 



home. html 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" 

"http : //www. w3.org/TR/html4/frameset.dtd"> 
<html> 
<head> 

<title>Home Page Content</ti tl e> 
</head> 
<body> 

<hl>Acme Home Page</hl> 

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy 
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi 
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis 
nisi ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in 
hendrerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat 
nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit 
praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> 

<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper 
suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel eum 
iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium 
dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio 
dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te 
feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, 
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat 
vol utpat . </p> 

<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse 
molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros 
et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



200 PartM ♦ HTML/XHTML Authoring Fundamentals 



augue diiis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, 

consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet 

dolore magna aliquam erat volutpat. Ut wisi e n i m ad minim veniam, quis nostrud 

exerci tation ullamcorper suscipit lobontis nisi ut aliquip ex ea commodo 

consequat . </p> 

</body> 

</html> 



Nested Framesets 



You have seen how to create rows and columns using framesets. However, what if 
you want a little of both? For example, consider the layout shown in Figure 12-10. 



] Nested Framesets - Microsoft Internet Explorer 



- h;x; 



File Edit View Favorites Tools Help 



o - o - a a & P 

Address 



^ '■;• 



0- §» m ■% 



|http://localho5t/Criapterl2/FiglO/frame5et.htrnl 



If 



Banner 



Navigation 



Content 



*j Local intranet 



Figure 12-10: A frameset with a combination of rows and columns. 



In such cases, you need to nest one frameset inside of another. For example, the 
following frameset code results in the layout shown in Figure 12-10: 



(frameset rows = "Z0"/,,*"> 

<frame name="banner" src="banner . html "></f rarne) 



Pl:KOA 

WY022-12 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



Chapter 12 ♦ Frames 201 



<frameset cols = "30%,*"> 

<frame name="nav" src="navi gat i on . html "></f rame> 

<frame name="content" src="home . html "></f rame> 
</f rameset) 
</f rameset) 

To achieve the layout, a column-based frameset is nested inside the second row of 
the row-based frameset. In essence, the second row of the top frameset becomes its 
own frameset. You could conceivably nest other framesets within this layout, but 
using more than two or three frames tends to clutter the document and confuse the 
user. 

Note The_pa rent and_top values of the anchor tag's target attribute were men- 

tioned earlier in this chapter. Looking at the example in this section, you can 
see how those two values would each affect the target. 

The _pa rent value causes the content to load within the frameset, that is the 
immediate parent of the current frame. For example, using _pa rent in a link 
within the content frame would cause the specified content to load in the 
area defined for the column-based frameset. 

The _top value causes the content to load within the top-most frameset. For 
example, using _t op in a link within the content frame would cause the spec- 
ified content to load in the area defined for the row-based frameset, effectively 
taking up the entire user agent window. 



Inline Frames 



Inline frames were conceived as a better method to allow smaller pieces of content 
to be incorporated in scrollable containers within a larger document. Although you 
can use regular framesets to create individually scrolling regions, the layout is 
somewhat hampered by the stringent row and column layout design inherent in 
framesets. 

Figure 12-11 shows a sample inline frame placed in a document. Note that the frame 
is truly "inline" — that is, completely enveloped by the document around it. 

Note Inline frames are not fully supported by all user agents. Inline frames are only 

safe to use if you are relatively certain that your entire audience will be using 
an <i frame) compatible browser to view your documents. If this is not the 
case, you should stay away from inline frames, or code your documents to offer 
incompatible browsers an alternative. See Chapter 25 for more information 
about making your documents cross-browser compatible. 

If you do decide to utilize inline frames, keep in mind that, like other frame 
constructs, your documents will only validate against frameset DTDs. 

Inline frames are accomplished with the <i frame) tag. This tag has the following, 
minimal format: 

<iframe src="url of content"X/i frame) 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



202 PartM ♦ HTML/XHTML Authoring Fundamentals 



Q Home Page Content - Microsoft Internet Explorer 



- n£) 



File Etlit View Favorites Tools Help 

he:'. <* ^ 



o © 



- Si B % 



Address g) http://localhost/Chapterl2/Figll/ 



I! 



Go 



Acme Home Page 



Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed diam nonurnmy nibh euismod 
tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis 
nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex ea cornmodo consequat. Duis 
autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium dolore 
eu feugiat nulla facilisis at vero eros et accumsan et lusto odio dignissim qui blandit praesent 
luptaturn zzril delenit augue duis dolore te feugait nulla facilisi. 



Products 

Lorem ipsum dolor sit amet, 
consectetuer adipiscinn elit, sed diam v 



Ut wisi enirn ad rninirn veriarn, quis nostrud exerci 

tation ullamcorper suscipit lobortis nisi ut aliquip ex ea 

cornmodo consequat. Duis autem vel eurn inure dolor in 

hendrerit in vulputate velit esse molestie consequat, vel 

ilium dolore eu feugiat nulla facilisis at vero eros et 

accumsan et iusto odio dignissim qui blandit praesent 

luptaturn zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, 

consectetuer adipiscing elit, sed diam nonumrny nibh euismod tincidunt ut laoreet dolore magna 

aliquam erat volutpat. 

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium 
dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent 
luptaturn zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, 



V 



I Done 



Vj Local intranet 



Figure 12-11: 

document. 



Inline frames define separate scrollable regions truly inline within the 



The <i frame) 
Table 12-3. 



tag has a handful of additional attributes. These are listed in 



Table 12-3 
The <iframe> Tag Attributes 



Attribute 


Value(s) 


Use 


align 


left 


Alignment of the frame to 




right 


surrounding text 




top 






middle 






bottom 





frameborder 



= no border 

1 = border (default) 



Whether the frame should 
have a visible border 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



scrolling 



Chapter 12 ♦ Frames 203 



Attribute 


Value(s) 


Use 


height 


pixels % 


The height of the frame 


longdesc 


url 


A URL to a document containing the 
long description of the frame 


marginheight 


pixels 


The size of the internal top and 
bottom margins of the frame 


marginwidth 


pixels 


The size of the internal left and right 
margins of the frame 



name of frame 



yes 
no 
auto (default) 



width 



url 



pixels % 



The name of the frame (for use in 
scripting and otherwise referencing 
the frame and its properties) 

Whether the frame should 
have scrollbars or not 



The URL of the content to display in 
the frame 

The width of the frame 



These attributes function exactly like their frame-based kin. It is recommended that 
you use as many attributes as possible to more closely specify howyour <i f rame> 
layout will be rendered. 

The following code was used for the document displayed in Figure 12-11. 

frameset.html 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" 

"http : //www. w3.org/TR/html4/frameset.dtd"> 
<html> 
<head> 

<title>Home Page Content</ti t 1 e> 
</head> 
<body> 

<hl>Acine Home Page</hl> 

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing el it, sed diam nonummy 
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi 
enim ad minim veniam, quis nostrud exenci tation ullamcorper suscipit lobortis 
nisi ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in 
hendnerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat 
nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit 
praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> 

<iframe name="productf rame" src="products . html " 

heigh t="100px" wi dth="250px" 

a 1 i gn="ri ght" f rameborder="l" ma rgi nhei ght="5px" 

marginwidth="5px" scrolling="auto"> 
</i f rame> 



Pl:KOA 
WY022-12 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:2 



204 PartM ♦ HTML/XHTML Authoring Fundamentals 



T 

er 
zz 
do 
ti 
mi 
ut 
</ 
</ 



t wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper 
it lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel 
iure dolor in hendrerit in vulputate vel it esse molestie consequat, 
1 urn dolore eu feugiat nulla facilisis at vero eros et accumsan et 
odio dignissim qui bland it praesent luptatum zzril delenit augue duis 
te feugait nulla facilisi. Lor em ipsum dolor sit amet, consectetuer 
ing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore 
liquam erat volutpat.</p> 
uis autem vel eum iriure dolor in hendrerit in vulputate velit esse 
ie consequat, vel ilium dolore eu feugiat nulla facilisis at vero 
t accumsan et iusto odio dignissim qui blandit praesent luptatum 
elenit augue duis dolore te feugait nulla facilisi. Lor em ipsum 
it amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod 
nt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad 
eniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi 
uip ex ea commodo consequat . </p> 



products .html 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" 

"http : //www. w3.org/TR/html4/frameset.dtd"> 
<html> 
<head> 

<title>Product Page Content</title> 
</head> 
<body> 

<h3>Products</h3> 

<p>Lorem ipsum dolor sit amet, consectetuer adipisc- 
ing elit, sed diam nonummy 

nibh euismod tincidunt ut laoreet dolore magna aliquam enat 
enim ad minim veniam, quis nostrud exerci tation ullamconpen 
nisi ut aliquip ex ea commodo consequat. Duis autem vel eum 
hendrerit in vulputate velit esse molestie consequat, vel i 1 
dolore eu feugiat 

nulla facilisis at vero eros et accumsan et iusto odio digni 
praesent luptatum zzril delenit augue duis dolone te feugait 
i s i . < / p > 
</body> 
</html> 



vol utpat 
s u s c i p i 
iriure d 
1 urn 

s s i m qui 
nulla f 



. U t wisi 
t lobortis 
o 1 o r in 



blandit 
i c i 1 - 



Summary 



This chapter introduced the concept of frames, including the relatively new inline 
frame construct. Using frames or inline frames, you can insert separately scrollable 
and formatted regions inside a larger document. As with most older HTML 
technologies, you should take care when choosing to use frames — in many 
instances, you would be better off learning and using CSS instead. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Forms 



HTML's somewhat humble beginnings were receive-only; 
that is, the user could receive data, but was not 
expected to be able to send data. However, that was quickly 
realized as a deficiency of HTML — with the user agents being 
run in graphical environments with rich user interfaces, 
creating a similar interface for which to allow users to submit 
data seemed a natural extension. 

Today, forms comprise a complex yet flexible framework to 
allow users basic controls. These controls can be used to 
provide input back to scripts or to submit data. This chapter 
delves into the particulars of HTML forms. 



Understanding Forms 



HTML forms simply place a handful of GUI controls on the user 
agent to allow the user to enter data. The controls can allow 
text input, allow selection of predefined choices from a list, 
radio or check boxes, or other standard GUI controls. 

After the data is entered into the fields, a special control is 
used to pass the entered data on to a program that can do 
something useful with the data. Such programs are typically 
referred to as form handlers because they "handle" the form 
data. 

The following code shows a basic HTML form whose output is 
shown in Figure 13-1. 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

< t i 1 1 e > A Simple Form</title> 
</head> 
<body> 
<form act i on="f ormhandl er . php" method="post"> 

<table eel 1 spaci ng="20"> 

<tr><td> 

< I - - Text boxes - -> 

<p><label f or="f name">Fi rst Name: </label> 










♦ ♦ ♦ ♦ 

In This Chapter 

Understanding Forms 

Inserting a Form 

Form Field Types 

Tab Order and Keyboard 
Shortcuts 

Preventing Changes 

Fieldsets and Legends 

Form Scripts and Script 
Services 




205 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



206 PartM ♦ HTML/XHTML Authoring Fundamentals 



] A Simple Form - Microsoft Internet Explorer 



., ri£! 



File Edit View Favorites Tools Help 

q-- o ■ a a ■■-;* p t? # & 



i * a b a 



Address g] http://localho.st/ChapteTl3/Fig01. html 



a 



First Name: 
Last Name: 



Address: 



± 



What product(s) are you 
interested in? 

Motherl 

Process 

Cases 

Power Supplies 



erboards W 
sssors 



Password: 



f~ Contact me via:' 

Email 

□ Postal Mail 



How soon will you be buying hardware? 



Submit Query ] | Reset | 



O ASAP 




O Within 10 business 


days 


O Within the month 




O Never! 





Leave site! 



Coupon 



a 



^J Local intranet 



Figure 13-1: A simple HTML form. 



<input type="text" name="fname" id="fname" 
size="20"Xbr> 
(label f or="l name">Last Name: </label> 

<input type="text" name="l name" id="lname" size="20' : 
C/p> 

( ! - - Text a rea - -> 

(pXlabel for=" address "> Ad dress:</labelXbr> 

<textarea name="address" id="address" 
cols=20 rows=4X/textarea> 
C/p> 

( ! - - Password - -> 

(pXlabel f or="password">Password : < / 1 a be 1 > 

<input type="password" name="password" i d="password' : 
size="20"> 
C/p> 



C/td> 

(td> 

(! -- Select 1 ist --> 

(pXlabel f or="products">What product(s) are you<br) 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 207 



nterested 


i n 


? </label><br> 


select name= 


■prod[]" i d="products" 


si ze="4"> 




<opt 


on 


d= 


'MB">Motherboards 


<opt 


on 


d= 


'CPU">Processors 


<opt 


on 


d= 


'Case">Cases 


<opt 


on 


d= 


'Power">Power Supplies 


<opt 


on 


d= 


'Mem">Memory 


<opt 


on 


d= 


•HD">Hard Drives 


< o p t i o n 


d= 


'Periph">Peripherals 


/sel ect> 






/p> 









( ! - - Check boxes - -> 
(fieldset) 

<legend>Contact me via: </legend> 
<p><input type="checkbox" name="emai 1 " id="email' : 
checked> 
<label f or="emai 1 ">Emai 1 </l abel ><br> 
<input type="checkbox" name="postal " id="postal"> 
<1 abel for="postal">Postal Mai K/l abel ></p> 
C/fieldset> 



/td> 




/tr> 




tr> 




td> 




I-- Re 


di 


p>How 


so 


fiel dse 


t> 


1 egenc 


X 


p X i n p 


ut 


id= 


"b 


<labe 


1 


input 


ty 


<labe 


l 


input 


ty 


<labe 


l 


input 


ty 


id="t 


uy 


<labe 


l 


/fiel dset 


/td> 





o buttons --> 

on will you be buying hardwa re?</p> 

/I egend> 

type="radio" name="buy" value="ASAP" 
uyASAP"> 

for="buyASAP">ASAP</label><br> 
pe="radio" name="buy" value="10" id="buylO"> 
f or="buylO">Wi thi n 10 business days</l abel ><br> 
pe="radio" name="buy" value="30" id="buy30"> 
f or="buy30">Wi thi n the month</l abel ><br> 
pe="radio" name="buy" val ue="Never" 
Never") 
for="buyNever">Never!</label></p> 



(td> 



Submit and Reset buttons 



(input type="submit"> 

(input type="reset"> 

(/p> 

(I-- Button --> 



(input type="button" name="Leave" value="Leave site! 
(/p> 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



208 PartM ♦ HTML/XHTML Authoring Fundamentals 



< ! - - Image - -> 

<input type="image" name="Coupon" src="coupon . jpg"> 

<!-- Hidden field --> 

<input type="hi dden" name="ref erredby" val ue="Googl e"> 

</td> 
</tr> 
</table> 

</f orm> 
</body> 
</html> 

Note Many form tags do not have closing tags. However, XML and its variants require 

that all elements be closed. If you are coding for XML or one of its variants (such 
as XHTML), be sure to close your tags by including the closing slash (/) at the 
end of tags that lack a formal closing tag. 



Inserting a Form 



You insert a form into your document by placing form fields within <f o rm> tags. The 
entire form or any of the tags can be formatted like any other element in your 
document, and can be placed within any element capable of holding other elements 
(paragraphs, tables, and so on). 

The <f ont> tag has the following, minimum format: 

<form acti on="url_to_send_data" method="get|post"> 

The action attribute defines a URL where the data from the form should be sent to be 
"handled." Although you can use just about any URL, the destination should be a 
script or other construct capable of correctly interpreting and doing something 
useful with the data. 

Note Form actions and form data handlers are covered in the section, Form scripts 

and script services, later in this chapter. 

The second attribute, method, controls how the data is sent to the handler. The two 
valid values are get and post. Each value corresponds to the HTTP protocol of the 
same name. 



HTTP GET 

The HTTP GET protocol attaches data to the actual URL text to pass the data to the 
target. You have probably noticed URLs that resemble the following: 

http : //www. example. com/forms. cgi?id=456Z7&data=Taarna 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 209 



The data appears after the question mark and is in name/value pairs. For example, 
the name i d has the value of 45677, and the name data has the value of 

Taarna. 



Note 



In most cases, the name corresponds to field names from the form and may 
relate to variables in the data handler. 



However, because the data is passed in the text of the URL, it is easy to 
implement — you can pass data by simply adding appropriate text to the URL used to 
call the data handler. However, GET is also inherently insecure. Never use GET to 
send confidential data to a handler, because the data is clearly visible in most user 
agents and can be easily sniffed by hackers. 



HTTP POST 

The HTTP POST method passes data encoded in the HTTP data stream. As such, it is 
not typically visible to a user and is a more secure method to pass data, but can be 
harder to implement. Thankfully, HTML forms and most other Web technologies 
make passing data via POST a trivial task. 



Additional <form> attributes 

The <f o rm> tag has many additional attributes. These attributes are listed in 
Table 13-1. 





Table 13-1 
<form> Tag Attributes 




Attribute 


Values 




Accept 


A comma-separated list of content types that the handler's server 
will accept 




accept-charset 


A comma-separated list of character sets the form data may be in 




Enctype 


The content type the form data is in 




Name 


The name of the form (deprecated, use the i d attribute instead) 




Target 


Where to open the handler URL (deprecated) 





Although you may not need these attributes in simple forms, these attributes can be 
very useful. The accept, accept-charset, and enctype attributes are invaluable 
for processing nontextual and International data. The i d attribute (formerly the 
name attribute) should be used to uniquely identify a form in your document, 
especially if you use more than one form in the same document. 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



210 PartM ♦ HTML/XHTML Authoring Fundamentals 



Field Labels 

The <1 abel > tag defines textual labels for form fields. The <1 abel > tag has the 
following format: 

<1 abel f or="i d_of_rel ated_tag">text_l abel</label> 

For example, the following code defines a label for a text box: 

<p><label f or="Fi rstName">Fi rst Name: </ 1 abel > 

<input type="text" i d="Fi rstName" name="Fi rstName" value="" 

size="30" maxlength="40"X/p> 

The role of the <1 abel > tag is accessibility-related. Most users can rely upon the 
layout of your forms to determine what labels go with what fields. However, if the 
user agent does not have a visual component, or if the user is visually impaired, the 
visual layout of the form cannot be relied upon to match labels and fields. The 
<1 abel > tag's for attribute ensures that the user agent can adequately match 
labels with fields. 



Text Input Boxes 



One of the most used fields of HTML forms is the simple text field. This field allows 
for the input of small pieces of text — names, addresses, search terms, and so on. 

The text input field tag has the following format: 

<input type="text" name="/le ld_ndme" val ue=" ; ni ti al _val ue" 
si ze=" si ze_of_fie Id" maxl ength="max_characters_a 1 1 owed"> 

Although all the attributes previously listed are not required, they represent the 
minimum attributes that you should always use with your text boxes. The following 
sample text box is designed to accept a name, appears 30 characters long, accepts a 
maximum of 40 characters, and has no initial value: 

<p>Name: <input type="text" name="username" value="" 
size="30" maxlength="40"X/p> 

The following code example defines a text box to accept an e-mail address. It 
appears 40 characters wide, only accepts 40 characters, and has an initial value of 

"emai l@exampl e . com": 

<p>Email: <input type="text" name="emai 1 " 

val ue="einai l@exampl e . com" size="40" maxl ength="40"X/p> 



Password Input Boxes 



The password input box is similar to the text box, but visually obscures data 
entered into the box by displaying asterisks instead of the actual data entered into 
the field. The following example displays a password field that accepts 20 characters. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 211 



<p>Password: <input type="password" name="password" value='" ! 
size="20" maxlength="20"X/p> 



Caution 



The password field only visibly obscures the data to help stop casual snoops 
from seeing what a user inputs into a field. It does not encode or in any way 
obscure the information at the data level. As such, be careful how you use this 
field. 



Radio Buttons 



Radio buttons are groups of small, round buttons that allow a user to choose one 
option in a group. The name "radio" button comes from how old-fashioned radios 
used to be tuned — you pushed one of many buttons to tune to a preset station. 
When one button was pushed, the rest were reset to the out position. Like those 
buttons, form radio buttons are mutually exclusive — only one of the group can be 
set. When one is selected, the others in the group are deselected. 

The radio button field has the following format: 

<input type="radio" name=" group_name" [checked="checked"] 
val ue=" va 1 ue_i f_se 1 ected"> 

Note that the value attribute defines what value is returned to the handler if the 
button is selected. This attribute should be unique between buttons in the same 
group. 

The following example code defines a group of radio buttons that allows a user to 
select their gender: 

<p>Gender : 

<input type="radio" name="gender" val ue="mal e"> Male 

<input type="radio" name="gender" val ue="f emal e"> Female</p> 

If you want a button s elected by default, add the checked attribute to the 
appropriate button's tag. 



Tip XML and its variants do not allow attributes without values. HTML will allow 

the checked attribute to be used with or without a value. To ensure your code 
remains as compliant as possible, it is suggested that you specify a checked box 
with the checked attribute as checked="checked" instead of just checked. 



, 



Check Boxes 



Check boxes are small, square boxes that are used to select non-mutually exclusive 
choices. They are so named because, when selected, they display a checkmark (or 
more commonly an "X") in the box like the check boxes in paper lists. 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



212 PartM ♦ HTML/XHTML Authoring Fundamentals 



The checkbox field has the following format: 

<input type="checkbox" name="fiel d_name" [checked="checked"] 
val ue=" va 1 ue_i f_sel ected"> 

As you can see, other than the mutually exclusive issue, check boxes are very similar 
in definition to radio buttons. The following example displays a check box allowing 
the user to select whether they receive solicitous e-mails: 

<p><input type="checkbox" name="spam_me" checked="checked" 
val ue="spam_me"> Add me to your email list</p> 

Note that the checked attribute can be used to preselect check boxes inyourforms. 
Also, just like radio buttons, the value attribute is used as the value of the check box 
if it is selected. If no value is given, selected check boxes are given the value of "on." 



List Boxes 



List boxes are used to allow a user to pick one or more textual items from a list. The 
list can be presented in its entirety, with each element visible or as a pull-down list 
where the user can scroll to their choices. 

List boxes are implemented using <sel ect> and <opti on> tags, and optionally the 

<optgroup> tag. 

The <sel ect> tag provides the container for the list and has the following format: 

<select name="name_of_fie Id" size=" 7 tems_to_show" 
[mul ti pi e="mul ti pi e"]> 

The <opti on> tag defines the items for the list. Each item is given its own 
<opti on> tag. This tag has the optional attributes shown in Table 13-2. 



Table 13-2 
<option> Tag Attributes 



Attribute Values 



Label A shorter label for the item that the user agent can use 

Selected Indicates that the item should be initially selected 

Value The value that should be sent to the handler if the item is selected; if omitted, the 

text of the item is sent item is selected; if omitted, the text of the item is sent 



An example of a minimum of <opti on> tags follows: 

<option>Sunday 
<option>Monday 
<opti on>Tuesday 
<opti on>Wednesday 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 213 



<opti on>Thursday 

<option>Friday 

<option>Saturday 

Occasionally, you might want to group options of a list together for clarity. For this 
you use <optgroup> tags. The <optgroup> tag encapsulates items that should be 
in that group. For example, the following code defines two groups for the preceding 
list of options, weekend and weekday: 



optgroup label="Wee 


ker 


d 


<option>Sunday 






<option>Saturday 






/optgroup) 






optgroup label="Wee 


kda 


y 


<option>Monday 






<option>Tuesday 






<option>Wednesday 






<option>Thursday 






<option>Friday 






/optgroup) 







Different user agents display option groups differently, but the default behavior is to 
display the option group labels above the options to which they apply as shown in 
Figure 13-2. 



fl A Select List - Microsoft Internet Explorer 



G(5)@ 



File Edit View Favorites Tools Help 

O ' O B H <S | P * * © 

Address I @ hr±p : //localhost/Chapter 1 3/Fig02 . html 



m a 






Select the days you are available: 



Weekend 



Sunday 
Saturday 
Weekday 

Tuesday 






^Done 



*j Local intranet 



Figure 13-2: Option groups are displayed in the list as nonselectable items. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



214 PartM ♦ HTML/XHTML Authoring Fundamentals 



Combining all three tags to create a list would resemble the following code: 



p>Select the days you are available: 




select name="Avai 1 Days" size="5" multiple- 


"mul ti pi e 


<optgroup 1 abel ="Weekend"> 




<option>Sunday 




<option>Saturday 




</optgroup> 




<optgroup 1 abel ="Weekday" 




<option>Monday 




<option>Tuesday 




<opti on>Wednesday 




<option>Thursday 




<option>Friday 




</optgroup> 




/sel ect> 




/p> 





Large Text Areas 



For large pieces of text, you can use the <texta rea > tag. This tag can accept textual 
input of up to 1,024 characters and uses a multiline text box for input. 

The<textarea> tag has the following format: 

<textarea name="name_of_flel d" col s=" number_of_co] umns" 
rows="numi>er_of_rok<s"></textarea> 

Note that the <textarea> tag is one of the few form tags that has an open and a 
close tag. If you want the field to have default content, the content should be placed 
between the tags. For example, the following code results in the initial form shown in 
Figure 13-3: 

<textarea cols="50" rows="6"> 

John Doe 

123 Main Street 

Anywhere, USA 

</textarea> 



T 'P Whatever is placed between the <textarea> tags appears verbatim in the 

\ text box when the form is first displayed. Therefore, it is important to carefully 

watch the formatting of your HTML code. For example, if you want the field to 

be initially blank, you cannot place the open and close tags on separate lines 

in the code: 



<textarea> 
</textarea> 

This would result in the field containing a newline character— it would not be 
blank. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 215 



) ATextarea - Microsoft Internet Explorer 



- ->E! 



File Edit View Favorites Tools Help 



Address g) http://localhost/Chapterl3/Fig03,html 



BB< 



John Doe 

123 Main Street 

Anywhere, USA 



* j Local intranet 



Figure 13-3: You can set a default value for the <textarea> tag by placing content 
between the open and close tags. 



Note 



Note that the text entered into the <textarea> field wraps within the width of the 
box, but the text is sent verbatim to the handler. That is, where the user enters line 
breaks, those breaks are also sent to the handler. However, the wrapped text 
(without hard line breaks) is sent without breaks. 

Previous versions of HTML supported a wrap attribute for the <textarea> 
tag. This attribute could be used to control how text wrapped in the text box 
as well as how it was sent to the handler. Unfortunately, user agent support for 
this attribute was inconsistent— you could not rely on a browser to follow the 
intent of the attribute. As such, the attribute has been deprecated and should 
not be used. 



Hidden Fields 



Hidden fields are used to add data to the form without displaying it to the user. The 
hidden field has the following format: 

<input type="hi dden" name=" name_of_fiel d" 
val ue=" va 1 ue_of_fie 1 d"> 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



216 Part " ♦ HTML/XHTML Authoring Fundamentals 



Other than not being visibly displayed, hidden fields are like any other field. Hidden 
fields are used mostly for tracking data. For example, in a multipage form, a u s e r i d 
field can be hidden in the form to ensure that subsequent forms, when submitted, 
are tied to the same user data. 

Keep in mind that hidden fields do not display on the user agent but are still visible 
in the code of the document. As such, hidden fields should never be used for 
sensitive data. 



Buttons 



Occasionally, you might have need for additional, custom buttons on your form. For 
those cases, you can use the button field. This field has the following format: 

<input type="button" name=" ndme_of_fiel d" 
val ue=" text_for_button"> 

This tag results in a standard graphical button being displayed on the form. The 
following code example results in the button shown in Figure 13-4: 



] A Textarea - Microsoft Internet Explorer 



- nQ 



File Edit View Favorites Tools Hel|> 

,j - .. i3 m •& ] p * • © I ' & i^ 



* 



Address 



] http://localhost/Chapterl3/Fig04,html 



BB< 



Buy Now! 



\£ Local intranet 



Figure 13-4: You can use the button field to add custom buttons to your form. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 217 



<input type="button" name="BuyNow" 
value="Buy Now!"> 

Buttons by themselves, however, are useless on a form. To have the button actually 
do something, you will need to link it to a script via the o n c 1 i c k or other attribute. 
For example, the following code results in a button that, when clicked, runs the 
script "buynow": 

<input type="button" name="BuyNow" 

value="Buy Now!" oncl i ck="Ja vaScri pt : buynow( ) "> 



Images 



Images provide a graphical means to convey a message. Using the image type of the 
<i nput> tag you can add images to your form, an image that can be used along with 
other form elements to gather data. The image field has the following format: 

<input type="image" name=" name_of_f\e~l d" 
src=" url _to_i mage_fil e"> 

However, like the button field, image fields by themselves do not provide any actual 
form controls. To use the image for input purposes, it must be linked to a script. The 
following example causes the image buy now . j pg to be displayed on a form. When 
the image is clicked, the script buynow is run: 



<input type="image" name="buynow" src= 
onclick="JavaScript:buynow()"> 



3uyn0w.jpg 



File Fields 



File fields allow a user to browse for a local file and send it as an attachment to the 
form data. The file field has the following format: 

<input type="file" name="name_of_fiel d" 
si ze="di spl ay_si ze_of_fiel d"> 

The file field results in a text box with a button that enables the user to browse for a 
file using their platform's file browser. Alternately, the user can simply type the path 
and name of the file in the text box. Figure 13-5 shows an example of a file field in 
Internet Explorer. 

However, in order to use this control in your forms you must do the following: 



4- Specify your form as multipart, which allows the file to be attached to the rest 
of the data. 

♦ Use the POST, not the GET, method of form delivery. 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



218 PartM ♦ HTML/XHTML Authoring Fundamentals 



] ATextarea - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



o - © ■ a a <£ p * * « a- a ■ 



Address @ http://localho5t/Criapterl3/Fig05.html 



Browse.. 



b@q 



it 



BB< 



"i 



V| 



* J Local intranet 



Figure 13-5: The file field allows a user to send a local file. 



This means your <f o rm> tag should resemble the following: 

<form acti on=" form_hand] er" method="post " 
enctype="form/multipart"> 



Submit and Reset Buttons 

Submit and reset buttons provide control mechanisms for users to submit the data 
entered to a handler and reset the form to its default state. These buttons have the 
following format: 

Submit button 

<input type="submi t" [va 1 ue="text_f or_button"] > 

Reset button 



(input type="reset" [val ue="text_f or_button"] 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 21 



The value attribute for both tags is optional — if this attribute is omitted, the 
buttons will display default text (usually "Submi t" and "Reset," but is ultimately 
determined by the user agent). 

The submit button, when clicked, causes the form to be submitted to the handler 
specified in the <form> tag's action attribute. Alternately, you can use the 
onclick attribute to call a script to preprocessing the form data. 

The reset button, when clicked, causes the form to be reloaded and its fields reset to 
their default values. You can also use the oncl i c k attribute to change the button's 
behavior, calling a script instead of reloading the form. 

T 'P Use of oncl i ck to change the reset button's behavior is not recommended. 

Using oncl i ck to cause the submit button to run a script for preprocessing is 
an expected process, but the reset button should always simply reset the form. 
If you need a button to perform some other function, use a custom button field 
that is appropriately labeled. 

Tab Order and Keyboard Shortcuts 

Two additional attributes, ta bi ndex and access key, should be used with your 
form fields to increase their accessibility. 

The tabi ndex attribute defines what order the fields are selected in when the user 
presses the Tab key. This attribute takes a numeric argument that specifies the field's 
order on the form. 

The access key attribute defines a key that the user can press to directly access the 
field. This attribute takes a single letter as an argument — that letter becomes the key 
the user can press to directly access the field. 



Note 



Keys specified in access key attributes usually require an additional key to be 
pressed with the key. For example, user agents running on Windows require 
the Alt key to be pressed along with the letter specified by access key. Other 
platforms require similar keys— such keys typically follow the GUI interface con- 
ventions of the platform. 

The following example defines a text box that can be accessed by pressing Alt+F (on 
Windows platforms), and is third in the tab order: 

<p><label for="Fi rstName"Xu>F</u>i rst Name: </l abel > 
<input type="text" i d="Fi rstName" name="Fi rstName" value="" 
tabindex="3" accesskey="F" size="30" maxl ength="40"X/p> 



Preventing Changes 



There are two ways to display information in common form fields but not allow a 
user to change the data — by setting the field to read-only or disabled. 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



220 PartM ♦ HTML/XHTML Authoring Fundamentals 



You can add the readonly attribute to text fields to keep the user from being able to 
edit the data contained therein. 

The d i s a b 1 e d attribute effectively disables a control (usually graying out the 
control, consistent with the user agent's platform method of showing disabled 
controls) so the user cannot use the control. 

The following code shows examples of both a read-only and a disabled control. The 
output of this code is shown in Figure 13-6. 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

< t i 1 1 e > A Textarea</ti tl e> 
</head> 
<body> 



j ATextarea - Microsoft Internet Explorer 



- -!•-' 



File Edit View Favorites Tools Help 

o - e • b a & p -t-- * e\e>- & » 



Address $£] http://localhost/Chapterl3/Fig06,html 



"0B* 



Customer Code 
(readonly): 



Zip Code (disabled): 



X234GG 



a: 



*-_j Local intranet 



Figure 13-6: Disabled and read-only fields can be used to show data without the 
data being edited. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 221 



<form acti on="f ormhandl er . php" method="post"> 

<table eel 1 spaci ng="10" wi dth="600"> 

<tr><td wi dth="25%"> 

<p>Customer Code ( readonl y ) : </p> 

</td><td> 

<input type="text" size="12" val ue="X234GG" 
readonl y=" readonly "> 

</td></tn> 

</table> 

<tr><td> 

< p > Z i p Code (disabled) :</p> 

</td><td> 

<input type="text" size="10" value="" 
di sabl ed="di sabl ed"> 

</tdX/tn> 

</table> 
</f onm> 
</body> 
</html> 

Although the two attributes make the fields look similar on screen, the readonly 
field can be selected, just not edited. The di sabl ed field cannot be selected at 
all. 



T 'P Disabling a control that is not applicable in certain instances is common practice. 

% For example, international addresses do not have a U.S. ZIP code. If a user 
indicates that they have an international address, you might decide to disable 
the ZIP code field so they do not enter data in that field. 

You can use client-side scripts to dynamically disable controls. Use onbl ur or 
onchange attributes to call a script from fields that could change the enabled 
status of other fields— those scripts check the data entered and enable or dis- 
able other fields by changing the value of that field's disabled attribute. More 
information on such techniques can be found in Chapters 25 and 26. 



Fieldsets and Legends 



Sometimes, it is advantageous to visually group certain controls on your form. This 
is a standard practice for graphical user agents, as shown in Figure 13-7. 

The <fieldset> tag is used as a container for form elements and results in a thin 
border being displayed around the elements it surrounds. For example, the following 
code results in the output shown in Figure 13-8. 



(flel dset> 

<p>Gender: <bn> 

(input type="nadio" name="genden" val ue="mal e"> Male <br> 

(input type="nadio" name="genden" val ue="f emal e"> Female</p> 

(/fieldset) 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



222 PartM ♦ HTML/XHTML Authoring Fundamentals 



Internet Options 



General Security Privacy Content Connections Programs Advanced 



-Home page- 



You can change which page to use for your home page. 
Address: http://localho5t/| 



Use Current ~| | Use Default"] | UseBlank^ 



-Temporary Internet files- 



Pages you view on the Internet are stored in a special folder 
for guick viewing later. 



| Delete Cookies... | | Delete Files... | | Settings... | 



- History 



The History folder contains links to pages you've visited, for 
quick access to recently viewed pages. 



Days to keep pages in history: |20 gg I Clear History 



Colors.. 



Fonts.. 



Languages... Accessibility.. 



OK 



Cancel 



Apply 



Figure 13-7: Grouping controls allows a user to 
better understand a form's organization. This is 
standard in GUI interfaces, as demonstrated in this 
Windows Internet Explorer dialog box. 

The <1 egend> tag allows the surrounding <fiel dset> box to be captioned. For 
example, the following code adds a caption to the previous example. The output of 
this change is shown in Figure 13-9. 

<fiel dset> 

<p><l egend>Gender </legend> 

<input type="radio" name="gender" val ue="mal e"> Male <br> 

<input type="radio" name="gender" val ue="f emal e"> Female</p> 

</fleldset> 



Form Scripts and Script Services 



As previously mentioned in the Understanding Forms section in this chapter, form 
data is typically passed to a data handler, a script or program that does something 
useful with the data. 



Form handlers typically do one or more of the following actions with the form data: 

♦ Manipulate or verify the data 

♦ E-mail the data 

♦ Store the data in a file or database 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 223 



] A Textarea - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



0-8 0@«i|P^#« 



m -a 



Address ^ http://localhost/Chapterl3/Fig08.htrnl 



p06o 



Gender: 
O Male 
O Female 



y;| 



\4 Local intranet 



Figure 13-8: The <fiel dset> tag can help add organization to your forms. 



There are many ways to construct a form handler, but the usual method is by using a 
server-side programming language to create a script that does what you need to the 
data. Common form handlers are created in Perl, Python, PHP, or other server-side 
programming language. 

Security is an issue that should be considered when creating form handlers. 
One of the earliest, most popular form handlers, f ormma i 1 . cgi , was found to have 
a vulnerability that allowed anyone to send data to the script and have it e-mail the 
data to whomever the sender wanted. This functionality was an instant hit with e-mail 
spammers who still use unsecured f o rmma i 1 scripts to send anonymous spam. 

Because form-handling scripts can be so diverse (performing different functions, 
written in different languages), it is hard to give tangible examples here. You should 
use a language you are comfortable with to create a form handler that does exactly 
what you want. 

If you want a generic form handler to simply store or e-mail the data, you can choose 
from a few routes. 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



224 PartM ♦ HTML/XHTML Authoring Fundamentals 



] A Textarea - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 

© * © a a & p * * © I - & 



m -$ 



Address @ http://localhost/Chapterl3/Fig09.html 



J Go 



f~ Gendet — 
O Male 
O Female 






*j Local intranet 



Figure 13-9: The <1 egend> tag can add captions to your fieldsets. 



Download a handler 

Several sites on the Internet have generic form handlers available. One of my 
favorites is the CGI Resource Index, http://cgi . resourceindex.com/. This 
site has several dozen scripts that you can download and use for your form 
handling. 



Use a script service 



Several services are also available that allow you to process your form data through 
their server and scripts. You may need such a service if you cannot run scripts on 
your server or want a generic, no-hassle solution. 

A partial list of script services is available at the CGI Resource Index, 

http : //cgi . resource!' ndex . com/. From the main page, select Remotely Hosted 
and browse for a service that meets your needs. 



PI: JYS 
WY022-13 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 13 ♦ Forms 225 



Summary 



This chapter showed you the particulars of HTML forms. It demonstrated how to 
include them in your documents and what each form tag can accomplish. The next 
two chapters introduce multimedia content and scripting — showing you how to 
include both in your documents. The next part of this book (Part III) dives into the 
deep subject of Cascading Style Sheets (CSS). 



PI: JYS 

WY022-13 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



226 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Multimedia 



C HlA P JA 



WmMW ultimedia on the Web has grown up. You can see 
IWI full-length movies on the Web, watch baseball games 
in real time on MLB.com, watch video news bulletins on CNN, 
and play games with other users. 

Generally, the best user experiences exist within the realm of 
broadband access, such as DSL and cable. Getting streaming 
video to work over a dialup connection is nearly impossible, 
but that doesn't completely rule out multimedia. However, 
most developers who are reaching for lofty goals in the 
multimedia world now target folks with fast 
connections — since a sufficient base of broadband 
connections have been installed. 

This chapter examines some of the multimedia platforms most 
frequently used on today's Web. Many, of course, have 
crowned Flash as the unofficial king of multimedia, but don't 
discount other technologies, especially if you're developing 
slideshows and video presentations. 



♦ ♦ ♦ ♦ 

In This Chapter 

Introducing Multimedia 
Objects 

Multimedia Plug-ins and 
Players 



Introducing Multimedia Objects 

Depending on the browser with which your users view your 
Web pages, multimedia can offer either a very rewarding or a 
very frustrating experience for your users. 

For example, if your users are using Netscape 3 to view a 
multimedia page, chances are they'll be taking a long journey 
that they'll ultimately cancel. This journey will consist of 
numerous dialog boxes and visits to Web pages for 
downloading plug-ins, which are small extensions to browsers 
used to extend a browser's capabilities. These downloads are 
necessary when a browser first encounters a multimedia 
object, because browsers don't have native support for such 
multimedia as Flash, RealAudio (now known as RealOne), and 
so on. 

In fact, you might be surprised to find out that browsers on 
today's market generally don't provide native support for the 
near ubiquitous Flash plug-in (Opera is the lone exception, 



227 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



228 PartM ♦ HTML/XHTML Authoring Fundamentals 




but it's usually a version or so behind the latest Flash players). Instead, the plug-in 
for Flash needs to be installed. However, Macromedia, the developer of Flash, has 
made the installation process so painless that Macromedia claims that Flash is now 
in more than 97% of all browsers. Those figures may be inflated by Macromedia's PR 
machine, but there is little question that the installed base is huge. You can be 
assured, however, that of those who don't have the plug-ins installed, many of them 
have older browsers such as Netscape 3. The reason for the difference is that 
modern browsers make plug-in installation a snap, whereas older versions required 
multiple visits to different sites and often numerous forms. 

Frankly, the best way to handle users with antiquated browsers is to simply bypass 
their multimedia options altogether, because their use of such an ancient browser is 
an indication that they don't care very much about the newest technology anyway. 
This can be done using browser-sniffing scripts. 

Browser sniffing, or browser detection, is a JavaScript-based process for detect- 
ing what kind of browser a user is using to view Web pages and displaying 
content based on the results of these findings. Chapter 26 explains how to 
develop these scripts. 

You can use a browser-sniffing script to send users with older browsers to 
HTML-only pages or write messages to their browser windows telling them they have 
crummy browsers (in a nice way, of course). 

Keep in mind that professional-looking multimedia requires a substantial investment 
in either your time or money (which you'll spend to get a professional to put it 
together for you). A long time ago, HTML purists cringed when they saw the 
notorious < b 1 i n k > tag. Today many Web site visitors' first reaction upon seeing 
Flash intros is to hunt for the "Skip Intro" button on these presentations. When 
making a decision about whether to use a multimedia object, ask yourself the 
following questions: 

♦ Does the multimedia object actually offer something I can't otherwise 
accomplish with HTML? 

♦ Does it truly enhance my Web site? 

♦ Will my users' browsers support the multimedia object I'm using? 

♦ Do I have the resources to make a genuinely professional multimedia 
presentation? 

If you can answer these questions in the affirmative, you're ready to go. 



Your multimedia options 

There are four general categories of multimedia objects: 

♦ Video clips — are supported by such applications as RealOne Player, the 

Windows Media Player, or Apple's QuickTime. Generally, when a file relying on 
one of these programs is accessed, the multimedia doesn't appear within the 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 229 



browser window (although it can). Instead, it spawns a window of the player 
application that plays the media. 

♦ Animations — can be generated by bit-map-based (paint) applications, such as 
Fireworks and Photoshop. These kinds of programs create GIF files consisting 
of several frames to produce an animation. Maybe you remember seeing a 
stack of papers in elementary school with a series of pictures, and as you flip 
through the stack, the image changed ever so slightly, creating an animated 
effect. The process is similar with animated GIFs. You see them everywhere 
these days, especially in banner ads. Most people consider them annoying, so 
use them with care and caution. 

♦ Sounds — can come in many formats, but again, you want to use them 
judiciously, because you can turn off your Web site visitors with them and even 
get them into trouble if they're visiting your Web page from the work place. 

4- Slide shows — are surprisingly useful for Web sites and can be created quite 
easily using PowerPoint or a free slide creation tool such as the presentation 
creation tool in OpenOffice . org's office suite. 

What about Java applets? 

Java applets, although not as common as they once were, are still used occasionally 
by some developers. The problem with Java applets is that they rely on a Java 
Virtual Machine installation that has proven to result in terrible inconsistencies 
across platforms. The only way around this is to hire an army of programmers to 
produce rock solid browser-sniffing scripts. One example of a reasonably successful 
deployment of Java-based applets was ESPN's GameCast, but even that has moved 
over to Flash. 



Including multimedia in your Web pages 

One kind of multimedia requires no plug-ins at all and can be written directly in your 
HTML. This is the animated GIF, which can simply be included in an i mg element, like 



<img src="myAnimati on . gi f " width="468" height="60"> 

As long as the animated GIF actually animates, you're in business. 

Most other multimedia requires the use of a plug-in, although you could consider 
some Dynamic HTML and CSS to be multimedia; and certainly, especially with some 
of the transition effects available in Internet Explorer through the use of both 
scripting and Microsoft's proprietary extensions to CSS, multimedia effects can be 
accomplished this way. 

Cross- Dynamic HTML and CSS effects are covered in detail in Chapter 27. 

Reference 



The standard way of embedding a multimedia object using HTML 4.0 is through the 
use of the obj ect element. The attributes available for the element are shown in 
Table 14-1. 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



230 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 14-1 
Attributes of the Object Element 



Attribute Name 



HTML Standard and Description 



archi ve (optional) 



classic) (optional) 



(HTML 4.0) A space-separated list of URIs for archives 
of classes and resources to be preloaded. Using this 
attribute can significantly improve the speed of an 
object 

(HTML 4.0) Specifies the location of the object's 
implementation by URL Depending upon the type of 
object involved, it can be used with or as an 
alternative to the data attribute 



codebase (optional) 


(HTML 4.0) Indicates the base URI for the path to the 
object file. The default is the same base URI as the 
document 


codetype (recommended) 


(HTML 4.0) Specifies the content type of data 
expected. If this is omitted, the default is the same as 
the type attribute 


data (optional) 


(HTML 4.0) Specifies the location of the object's data. 
If given as a relative URI, it is relative to the 
code-based URI 


height (optional) 


(HTML 4.0) Specifies the initial height in pixels or 
percentages of the element 


hspace (optional) 


(HTML 4.0) Defines the number of pixels on the 
horizontal sides of the element 


i d (optional) 


(HTML 4.0) (CSS enabled) Formats the contents of 
the tag according to the style id. Note: IDs must be 
unique within a document 


name (optional) 


(HTML 4.0) The name attribute assigns the control 
name to the element 


standby (optional) 


(HTML 4.0) This specifies a message that is shown to 
a user while the object is loading 


styl e (optional) 


(HTML 4.0) (CSS enabled) Formats the contents of 
the element according to the listed style 


type (optional) 


(HTML 4.0) Indicates the content type at the link 
target. Specify the type as a MIME-type. This attribute 
is case-insensitive 


vspace (optional) 


(HTML 4.0) Defines the number of pixels on the 
vertical sides of the element 


wi dth (optional) 


(HTML 4.0) Specifies the initial width in pixels or 
percentages of the element. 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 231 



You can also use child pa ram elements within an obj ect element to pass 
parameters to the multimedia object. These parameters are generally like little bits 
of helpful information that help fine-tune exactly how you want the object to behave. 
You can use Table 14-2 to review the pa ram element's attributes. 





Table 14-2 
Attributes of the param Element 


Attribute Name 


HTML Standard and Description 


Name 


Specifies the name of the parameter being passed to the object 


type (optional) 


Specifies the MIME type of the data 


val ue (optional) 


Specifies the value of the parameter being passed to the object 


Val uetype 


Specifies the type of value being passed 



The following example shows a Flash file embedded in an HTML document: 



< o b j e c t 


cl assi d=" 


codebase="http : // 


lash/swflash 


cab#v 


i d="ma r row" 


align 


<pa ram 


name= 


"alio 


<pa ram 


name= 


"movi 


<pa ram 


name= 


"loop 


<pa ram 


name= 


" q u a 1 


<pa ram 


name= 


" b g c o 


<embed 


src=' 


marro 


bgcol or 


="#ffffff" 


al i gn=' 


m i d d ' 


e" al 


type="e 


p p 1 i c a t i o n 


pi u g i n s 


page= 


"http 


< / o b j e c 


t> 





•clsid:d27cdb6e-ae6d-llcf-96b8-444553540000" 
'download.macromedia.com/pub/shockwave/cabs/f 
/ersion=5, 0,0,0" width="120" height="600" 
i = "mi ddl e"> 

DwScriptAccess" value="sameDomai 
ie" val ue="marrow. swf " /> 
val ue="f a 1 se" /> 

ity" value="high" /> 
)lor" value="#ffffff" /> 
jw.swf" loop="false" quality="hi 
width="120" height="600" name= 

lowScriptAccess="sameDomain" 
i/x-shockwave-flash" 

: //www.macromedi a.com/go/getflashplayer" / 



/: 



gh" 
"marr 



The key to using the param elements is that the multimedia object must understand 
what the parameters mean. So, you need to either have access to some 
documentation about how the multimedia object works and what kind of parameters 
it expects, or you need to get your hands on a tool that generates the HTML for you. 
In the case of Flash, its movie exporting facilities take care of this for you. Listing 14-1 
provides an example. 



Listing 14-1 : Embedding a Flash File Using an Object Element 

< 1 D0CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional //EN" "http : //www. w3 . org/TR/xhtml 1/DTD/ 
xhtml-transitional . d t d " > 



Continued 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



232 PartM ♦ HTML/XHTML Authoring Fundamentals 



Listing 14-1 : (continued) 



<html xmlns= 


="http: //www. w3.org/1999/xhtml" xml :lang="en" 


1 ang="en"> 




<head> 




<meta http -equi v="Content -Type" content="text/html ; 


cha rset=i so 


8859-1" /> 


<title>marrow</title> 


</head> 




<body bgcolor="#ffffff"> 


<object classid="clsid:d27cdb6e-ae6d-llcf -96b8 -4445 535400 


codebase="http://download.macromedia.com/pub/shockwave/ca 


flash/swflash 


cab#version=5, 0,0,0" width="120" hei ght="600" 


i d="ma rrow" 


al i gn="mi ddl e"> 


<param name= 


="al 1 owScri ptAccess" val ue="sameDomai n" /> 


<param name= 


="movie" val ue="marrow. swf " /> 


<param name= 


="loop" val ue="f al se" /> 


<param name= 


="quality" value="high" /> 


<param name= 


="bgcolor" va 1 ue="#f f f f f f " /> 


<embed src=' 


marrow. swf" loop="false" qua 1 i ty="hi gh" 


bgcol or="#f f f f f f " width="120" height="600" name="marrow" 


al i gn="mi dd" 


e" al lowScriptAccess="sameDomain" 


type=" appli cat ion/x- Shockwave -flash" 


pluginspage= 


="http: //www.macromedi a.com/go/getflashplayer" 


</object> 




</body> 




</html> 





bs/ 



Note the use of the deprecated embed element as a child element of the ob j ect 
element. The embed element is still needed for Netscape 4 and some other browsers, 
however, so use it if you're looking for cross-browser functionality. Keep in mind the 
following about the embed element: 

Do not include a name attribute with the ob j ect element when using the embed 
element, especially if it is the same name value as that of the embed element because 
it could cause confusion when scripting. 

Parameters are handled through the use of custom attributes, such as those shown 
in Listing 14-1. Notice, for example, the al 1 owScri ptAccess="sameDomai n" 
attribute/value pair. The a 1 1 owSc ri ptAccess attribute is not actually part of the 
embed element. Instead, it's a special attribute that Flash understands. These 
custom attributes have the same functionality as the object element's pa ram 
element children. Different plug-in vendors may require different configuration 
parameters. 

The pluginspage attribute is an attribute of the embed element. It manages the 
way in which a plug-in is obtained if it isn't installed in the browser. This 
attribute points to a page to get the plug-in if the plug-in is not detected by the 
browser. 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 233 



How the Eolas Lawsuit Will Affect You 



As this book was being written, Microsoft was trying to deal with losing a $52 1 million patent 
infringement lawsuit filed by Eolas, a company founded by Michael Doyle, former director of 
the University of California academic computing center. The patent governs the use of any 
object included in a Web page using the embed, object, or appl et elements. Although 
Microsoft has appealed the decision, future versions of Internet Explorer (beyond version 6) 
will present a pop-up window asking users if they wish to view an embedded application or 
media file. 

This does not affect objects that use no pa ram elements. 

There are some workarounds. One, obviously, is to not include any pa ram elements. That 
pretty much wipes out any hope of using Flash. Another is to embed the applications using 
script. 

The following example shows how to create a Web page that uses DHTML to load a Microsoft 
Windows Media® Player control. 

<HTML> 

<HEAD> 

<SCRIPT SRC="sample.js"></ SCRIPT) 
</HEAD> 
<B0DY> 

<SCRIPT> 

Repl aceContent ( ) ; 

</SCRIPT> 
</B0DY> 
</HTML> 

An ActiveX control can be inserted into a Web page by setting the innerHTML or outer- 
HTML property of an existing element, or by calling document .wri te (which is the health- 
ier, cross-browser method). The following script creates the Windows Media Player using 

document .wri te: 

function Repl aceContent () { 

document. wr i te ( '<0BJECT CLASS I D="CLSI D : 6BF52A52-394A- lld3- 
B153-00C04F79FAA6">' ) ; 

document. write( '<PARAM NAME="URL" 
VALUE="http://msdn.microsoft.com/workshop/'); 
document. wri te('samples/author/dhtml/medi a/drums. wav"/X/0BJECT>'); 



Multimedia Plug-Ins and Players 

There are several kinds of popular multimedia plug-ins and players. The following 
are the most popular: 



♦ Flash 

♦ RealOne 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



234 PartM ♦ HTML/XHTML Authoring Fundamentals 



♦ Windows Media Player 

♦ Adobe Acrobat Reader 



Flash 



Flash, which has become arguably the most prevalent multimedia format, began life 
as a plug-in for something called FuturePlayer. FuturePlayer was purchased by 
Macromedia, which has made significant refinements to the original product. 
Macromedia had enjoyed reasonable success with its own Shockwave format, which 
was quite similar to Flash files but generated by Macromedia Director. Macromedia 
did a good job of commingling the two formats and, eventually, Shockwave pretty 
much disappeared in favor of Flash. Today's Flash can display MP3-based video and 
sound, along with vector graphics, and can harness data sources from relational 
databases and XML. 

In fact, Flash has become a serious application platform in its own right, enabling 
developers to display changing data in real time. 



RealOne 

RealOne is a media player that reads video and audio files. Real, Inc., the developer 
of RealOne, was one of the first companies to introduce the concept of streaming 
audio to desktops. Streaming media (audio and video) is sent in real time through 
special servers. If you're doing professional-level streaming media, you'll want to see 
if your host provider (if you're using one) offers access to a Real Audio server. 

If you're planning on developing for RealOne, you can find comprehensive Software 
Development Kits (SDKs) and tutorials at this site: http : //www. real networks 
.com/resources/sdk/. 

You can create standards-based files that RealOne can understand by using the 
Synchronized Multimedia Language (SMIL), described near the end of this chapter. 
Figure 14-1 shows an instance of a RealOne player. 



Windows Media Player 



Windows Media Player has a huge installed base because it comes as part of the 
Windows operating system. Its functionality is virtually identical to RealOne, offering 
video and music playing capabilities. To properly display Windows Media Player 
files, you should use the ASX markup language, which is an XML-based proprietary 
language developed by Microsoft. 

When a user clicks an ASX link, the browser spawns an instance of the Windows 
Media Player. For example, refer to the following link: 

<A HREF="http : //webserver/path/yourfil e . asx">Li nk to 
Streaming Content</A> 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 235 



r O RsalOne Player 



Adverdsino.com C ac^ertfsement ) 



File Edit View Flay Favorites Tools Hep _ D X 

0:00/0:01 i£l -r 



^^ O N/ 



\? 



Q^N\ rs\ $in on home SAFEW/Ycom 
OUVU IU delivery 



Shop .inline for fresh, quaity items delivered to your home 



(^O®®©- 



@-o 



ft HDme X 1 '.0 ^ T ' Agassi http://hDme.real. com/? 



RealOne GUIDE 



"3® ( ) I s) 



SIPER^ASS TODAY 

MUSIC 

RADIO 

SPORTS 




.. NOVEMBER 4 



Month's Top Clicks 

E8 1, MusicVdeo; "S:aa s M=.m" 
H 2. Britney'; "Esquire" Spread 



My RealOne 



3. Madonra & Britney Video 



Get a FREE 14-day tral of 



CLICK MERE TO LEARN MORE 



P led se Siyn III 



L [&^_ Now Playing | (& web ^j My LIDrary (/} CD J Devices :r"!| Radio ^Channels *.^ search 

Figure 14-1: A RealOne player accessing the main Real portal. 

This links to the following file and opens up a Media Player: 

<ASX version = "3.0"> 
<TITLE> ASX Demo</TITLE> 
<ENTRY> 
<TITLE>A New Song</TITLE> 
<AUTHOR>Chuck Whi te</AUTH0R> 
<C0PYRIGHT>(c)2003 Chuck Whi te</COPYRIGHT> 
<!-- This is a comment. Change the following path to 
point to your ASF --> 

<REF HREF = 
"mm s://windowsmedi a server/path/ my song. asf" /> 

</ENTRY> 
</ASX> 

For the specifics of what the various elements mean in an ASX file, go to 

http://msdn.microsoft.com/library/default.asp?url=/nhp/Default. 
asp?contentid=28000411. 



QuickTime 



QuickTime has distinguished itself by consistently raising the bar on video quality. 
QuickTime has long been a staple in the Apple world, but its quality is so good it has 
made inroads into the Wintel world, as well. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



236 PartM ♦ HTML/XHTML Authoring Fundamentals 



The feature set is similar to RealOne and Windows Media Player. Like RealOne, you 
can create media shows for QuickTime using SMIL, as shown at the end of this chapter. 



Animations 



There are three main categories of animations. The simplest is an animated GIF file, 
but even those can be time consuming, because to make a nice animation requires 
that you create a new image for each frame of an animation. Another category 
of animation is a Java-based or ActiveX animation. Java is a machine-independent 
language that requires that the target user have a Java Virtual Machine (JVM) installed 
on his or her computer. Inconsistencies in JVMs have forced most Web animation 
aficionados to abandon Java as an animation platform. Active X animations are even 
more rare, because they're limited to Windows-based Internet Explorer browsers. 

This helps explain why the third category, Flash, has become so popular — along with 
the fact that Macromedia has created what can only be described as a genuine 
application environment within the Flash framework. 



Creating animated GIFs 



Including an animated GIF file is the easiest of all the multimedia tasks. You simply 
create one in a paint program that supports them, or find an inexpensive or free 
program that specializes in helping you create them. 

All Animated GIF creation programs are different, but their essence is the same. 
You start off with one frame, and when you want your image to change, you create 
another frame to represent that change. The frames can be on a complicated timeline, 
or as simple as the interface shown in Figures 14-2 and 14-3, which demonstrate 
an animated advertising banner being created using Macromedia's Fireworks. 

The animation creation software then generates an animated GIF file consisting of as 
many frames as you indicate. You can also set the amount of time between the frame 
changes, as shown in Figure 14-4. 

Figures 14-5 and 14-6 show the transition between one frame of a completed 
animated advertising banner and another. 



Keeping files sizes small 



Generally, you want to keep your file sizes small, and if you're creating advertising 
banners, the Web sites that run your ad will probably require you to keep them 
small. To keep your files small, keep in mind the following tips: 

♦ Use as few frames as possible. 

♦ Use as few colors as you can. This is where a higher-end animation program 
such as Fireworks (www . macromedi a . com) or DeBabelizer 

(www . equi 1 i bri um . com) comes in handy. They help reduce the number of 
colors in your animation without degrading quality. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



-«M^™^«^ 




U A 



Web 

njps 



Hefcj 



Animated GF (Document] @S^1 



150 200 550 30O 350 400 450 530 550 

I I I I I I I I I I I I I I I I I I I I I I I I I | I I I I I I I I I I I I I I 



>bu've hac a ong day. 

Are you sure you re 

redLty Lu ildrldFXjLt er LjfqJKtL? 



468 k 60 103K 



'Zl 



I* JMI 

1)0) jgi 



Dccument 
BannerlGMO 



Canvas | [ Canvas Size... \ [ Image Size... \ 



© 



Figure 14-2: The first frame of an animation built in Fireworks. 



IIJJ.IJJIIJIJJIII.IJU1HIW 

Fib Ei 



D Ef 



"t- l 




*/ Ai ifn T'np 

^ Auto Dffersnce 



Picpcitics.. 



TOT 
Are 

reacj , . . 

Hep 

Group Frames with 
r^ u | Rename Panel Groip 
Close Fane Gi 




250 300 35C UOO 450 

I I I I I I I I I I I I I I I I I I I I I I I I I 





Canvas | [ Canvas Size... \ [ Image Size... \ 




Figure 14-3: To build the second frame, you simply add the frame using the Frames and 
History palette. 



237 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



238 PartM ♦ HTML/XHTML Authoring Fundamentals 



T9HBHM 


!fl 


^^■jiHO] 


Options \ File | 


Animation I 


'Animated GIF Preyiew[7] 
: Adaptive 128 colors 
14.23K 2 sec rssekbps 


Sawed Settings: 

1 


V ±J 


GO [raj 




m 


Frame 1 


U 400 1100 sec. 


m 


Frame 2 


U 400 




>bu've had a long day. 

Are you sureyoure dtfl 

ready to start another project? 




Run Time: 8.00 sec. 








-H 


<P, 1 3 


- 


[•] Auto Crop 
[^] Auto Difference 


*lol 




M | [l | V It 


tPlctlin* ..vJiGBH "IN 




EnporL. J OK 


f Cancel 1 





Figure 14-4: Changing the time interval between frame changes. 



-^ ^X0MM,m-ti*i 



oksUrtfl.ey\rhapterl4\binner4*3xtO_ :1 if- Ht 



hie Ldit View haviirites lools Help 



o 

Back 



El 

btop Refresh 



ft 

Home 



P & * 

search r-avcntes Neda 



>bu've had a lors day. 

Are you sure you're 

ready to ststtarrother project? 



Figure 14-5: Transitioning between one frame of a completed animated advertising 
banner and another, part one. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 239 



L^—pj^^^^ 



; File Edit yew 



Favor tes Tumls Help 



o 

Bock 



o 

Forward 



Stop 



RcFrcsh Hone 



P 

Scorch 



Medio 



Letuscto thecooking foryou. , 

low fat, low carb, and wgetaTar meats for £ H U 6 6 ROUS 

tfe hem; o' office. L>eliwred to your door. 



S 



I 



-Vi* 



Figure 14-6: Transitioning between one frame of a completed animated advertising banner 
and another, part two. 



Creating a Flash file 



Creating a Flash file is not so easy. Flash is enormously popular because it's a very 
powerful tool, but in the wrong hands it can spell disaster. The Flash file format 
(with a . fla extension) is the starting point of a Flash presentation on the Web. 
Figure 14-7 shows two instances of the same Flash file side by side, each in a 
different stage of the animation. This kind of animation is much more sophisticated 
than an animated GIF, because it runs programmatically based on a scripting 
language similar to JavaScript named ActionScript. In the case of the animation 
shown in Figure 14-7 (downloadable as ma rrow . swf and ma rrow .fla), the text falls 
quickly into the pane to mimic someone quickly typing code. This is done through 
the use of an external XML file, which is simply looped through over and over 
again. 



Done correctly, Flash is a marvelous tool, but it isn't the most intuitive program on 
earth, so be prepared for a bit of a learning curve if you want your Flash 
presentations to look professional. You've already seen how to include a Flash 
presentation in your HTML page in a previous explanation of how to use the object 
element. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



240 PartM ♦ HTML/XHTML Authoring Fundamentals 



3 marrow - Microsoft Internet Explorer i-j(nj(xj 3 marrow - Microsoft Internet Explorer 



File Edit View Favorites Tools Hi 



: File Edit View Favorites Tools 


*| # 


Q . O 

: Back Forward 


» 


: Address 


i§| pterl4\flash\L1401.html V 


H 



sr &1&0 



Wish You 

Could Write 

XSL Code 

This Fast? 

Now You 



< hs 1 : uar lab It 



<K5l:copy-of 
s e le a t = " fpE ascLij t ' 7> 

■^Ksl:copy-of 
£eleGt= l ^TSH5l:riod±- 
set ( $i-rNer£aseL±stEJjein. 

■=:,■' Mil: i.TLcial' It :=■ 
<hs 1 :vaxiablc 
select= l ^msHsl:node- 



ui n^o 



*J Mu rnmm ih^f 



A' 



o 

Back 



Forward 



Address @ \Chapterl4\flash\L1401.html Y j j Go 



■r. ^ h: <:. Of? 



Wish You 

Could Write 

XSL Code 

This Fast? 

Now You 

Can. 



< / its 1 : o -tht Twis c > 
< /msI : otioost> 
</nsl:ttrrplat4> 
<hs1 : template 

mat ch= "* [name space - 



Figure 14-7: A Flash animation in action. 



Video Clips 



* 



There are three major types of video: 

4- MPEG (short for Motion Picture Experts Group), which includes video versions 
of MP3 

4- AVI, used primarily on Windows 

4- QuickTime, originally an Apple-only format but now widely available on 
Windows and Apple machines 



You can either link to video files or embed them directly into your Web page. 
Generally, it's best to give people fair warning that your Web page contains a video, 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 241 



so you should at a minimum link to the page that contains the embedded video, and 
then embed the video into that linked page. You can also embed video in 
presentations made with Flash MX and above (Flash MX 2004). In fact, Flash MX 
handles video so well that many people are turning to that as their presentation 
environment for video. Flash itself is not video (unless you consider the animations 
it creates video), but is instead a presentation platform that can include video, 
music, and pictures as part of the finished presentation. 

To link to a video file, simply include it in an a element, as in the following example: 

<a href="myVi deo .mpg">Thi s is a movie 1 i n k . < / a > 

When a user clicks the link and has the supporting software, the video will play in 
the user's default media player. 

You can also use the object element (and the embed element if you're targeting 
Netscape users), but keep in mind that there are some preferred ways of including 
multimedia that have already been discussed. In other words, you can embed a 
video, such as an mpg file, directly in your Web page, but you'll be at the mercy of 
whatever system setup your user has. It's better to target a specific or group of 
specific media players by including your video in a SMIL or ASX file (discussed later 
in this chapter), or each of them, then giving your users a choice of which they'd like 
to view. For example, you could provide a link that says, "Window Media Player 
Users Click Here" for ASX files, and then target QuickTime and RealOne users with 
SMIL documents. 



Sounds 



Most of us are aware of the copyright infringement issues that can accompany 
copying and/or distributing MP3 files. You can include sound the same way you 
include video, but do be careful of copyright infringement. It may not seem obvious 
that copying music is copyright infringement, but there is absolutely no legal haze 
regarding copying and distributing content. You can't do it without permission 
without expecting a lawsuit. In addition to MP3, there are four additional fairly 
common sound formats: 

♦ Musical instrument digital interface (MIDI, pronounced "middy") is basically 
synthesized music. If you've ever seen those electric pianos in the store, or, 
better yet, you have one, you have seen a device that can generate a MIDI file. 
The advantage is that the files are small. The disadvantage is that if the 
individual making the music isn't skilled, the result will be poor. 

♦ AU is a fairly low-quality but small file size sound format most often found in 
Java applets. 

4- Audio Interchange File Format (AIFF) is a Macintosh-based format that is now 
found on other platforms as well. 

4- WAV is a Windows-based sound format of reasonably high quality. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



242 PartM ♦ HTML/XHTML Authoring Fundamentals 



Needless to say, MP3 has surpassed these other formats by a wide margin in 
popularity. 

You can also include background sound to an Internet Explorer page using the 
bgsound element: 

<bgsound src="bi gsounds . wav"> 

Or, in Netscape, you can use the embed element: 

<embed src="bi gsounds .wav" autostart="true"> 

Note Just keep in mind that startling someone with background music when they're 

visiting your page is a cruel act and isn't likely to be forgiven, or rewarded 
with a return visit to your Web site, unless your site happens to be so heavily 
music-oriented that your visitors expect it. 



Slide Shows 



Slide shows are a nice way to distribute presentations you may have given to groups 
of people who might want to see the slide show you used during the presentation 
again. You can basically take a slide show you created for such an event and port it 
directly to the Web. You can create presentations from PowerPoint, which is a widely 
distributed slideshow presentation software tool. However, if you don't have 
Powerpoint and/or don't want to shell out the money for a PowerPoint license, you 
can use freeware such as OpenOffice. The following sections look at how to export 
presentations from both of these programs. 

Exporting PowerPoint presentations to the Web 

To create PowerPoint Presentations for the Web, you need to be certain your 
settings are correct. This seems like a simple enough requirement, but access to the 
correct settings is hidden away somewhat. In PowerPoint 2002 and PowerPoint 2003, 
you'll find the Web settings in two places. 

You can choose your Web settings by going to Tools O Options. Choose the General 
tab (shown in Figure 14-8). From there, choose the Web Options . . . tab. 

Or, you can export your document as a Web page by going to File O Save As Web 
Page . . . You'll see a dialog box like that shown in Figure 14-9. Instead of clicking Save, 
click the Publish button just under the file list in the dialog box. After clicking 
Publish, you'll see a dialog box like that shown in Figure 14-10. Click the Web Options 
button for additional options, such as which browser(s) to target, the size of your 
images, and so on. When you click OK, you'll return to the Publish as Web Page 
dialog box, which also has a browser support option (a better one, in fact, because it 
lets you choose all browsers). Choose the directory you want to save the files to. If 
you're a novice, it's best to create a new directory, and then simply upload that new 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 243 



Save 



View 



Security 



General 



Spelling and Style 



Edit 



Print 



General options — 
HI Provide feedback with sound to screen elements 

entries 



Recently used file list: ] 4 * 



Link sounds with file size greater than 
User information 
Name 



100 



Kb 



Chuck White 



Initials: 



CEW 



Web Options. 



Service Options. 



OK 



Cancel 



Figure 14-8: The General Options tab in PowerPoint's Options 
dialog box. 



directory in its entirety to your server so you don't have to worry about managing 
files. When you're done, click Publish, and then upload the directory you saved your 
files to onto your server. 

Following either of the two preceding methods, you should now see the Web Options 
dialog box, as shown in Figure 14-11. 

This dialog box is your control panel for managing the way a PowerPoint 
presentation looks when it is delivered to the Web. It manages such settings as 
browser compatibility, screen size and resolution, and what format your graphics 
should be in. 

The controls are managed through the following group of tabs, named, successively, 
from left to right (top bullet being left and bottom being right): 



♦ General 

♦ Browsers 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



244 PartM ♦ HTML/XHTML Authoring Fundamentals 



Save in: 



My Recent 
Documents 



Desktop 



My Documents 



My Computer 



■J 

I Computi 

« 

My Network 
Places 



£)The Miraculous 5lideshow_files 



£) Chapter 14 



Q2 I 1ft X C| H - Too[s ~ 



Ek Save a copy and customize its contents Publish 



Page title: 


The Miraculous Slideshow 


| Change Title... | 


File name: 


ilJISEllEflllHIIEEIRIBSfilHIIBISIJ 


V 












Save as type: 


Single File Web Page (*,mht; *,mhtml) 


V 



Save 



Cancel 



Figure 14-9: PowerPoint's Save As Web Page... dialog box. 



Publish as Web Page 



JLJIIill ',",'lldi_! 

© Complete presentation 








O Slide number i 


C through 


c 




Custom show: 


Display speaker notes 






Web Options... 







O Microsoft Internet Explorer 4.0 or later (high fidelity) 

O Microsoft Internet Explorer 3.0, Netscape Navigator 3.0, or later 

© All browsers listed above (creates larger files) 

Publish a copy as 



Page title: The Miraculous Slideshow 
File name 



Change. 



C:\Documents and 5ettings\Chuck\Books\ Wiley \Chapterl 



Browse. 



[?) Open published Web page in browser 



Publish 



Cancel 



Figure 14-10: PowerPoint's Publish As Web Page dialog box. 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 24 



Web Options 



General 



Browsers 



Files 



Pictures 



Encoding Fonts 



Appearance 

•] Add slide navigation controls 
Colors: white text on black 



•] 5ho'.".' slide animation ■/-.■hile browsing 
•] Resize graphics to fit browser window 



OK 



Cancel 



Figure 14-1 1 : The Web Options dialog box. 



♦ Files 

♦ Pictures 
4- Encodings 

♦ Fonts 

Each of these options is briefly explained in the following sections. 



Note 



These specific instructions pertain to the latest edition of Microsoft Office, which 
as this book went to press was Office 2003. The tabs in PowerPoint 2002 (part 
of Office 2002) are slightly different, but you can still find most of the settings 
described on the Web Options interface or the Publish dialog box. For example, 
the browser settings in PowerPoint 2002 are found on the Publish dialog box 
because there is no Browser tab. 



Choosing options in the General tab 

The General tab lets you decide on your presentation's core settings (seen 
previously in Figure 14-11). 

If you choose to enable slide navigation controls, PowerPoint will insert the 
navigation controls into a small thin frame in a frame-based output. You can also 
enable PowerPoint animations, but you'll need to be sure your viewers can see them, 
and if they're running Netscape, Opera, or Safari, they probably won't. Generally, it's 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



246 PartM ♦ HTML/XHTML Authoring Fundamentals 



best to leave this unchecked unless you're on a corporate intranet that relies on MS 
products. 

You should also be sure to choose the option for resizing graphics to fit a browser 
window; otherwise, the graphics may stretch the Web page beyond the browser 
window's boundaries, forcing users to scroll left, which most people hate to do. 

Using the Browser tab 

The Browser tab (shown in Figure 14-12) lets you configure how to adjust the 
presentation for viewing in the various Web browsers. For full downward 
compatibility, you'll want to choose Microsoft Internet Explorer 3.0, Netscape 
Navigator 3.0, or later. 



Web Options 



General ! Browsers 



Files Pictures Encoding 



Fonts 



Target Browsers - 
People who view this Web page will be using: 



Microsoft Internet Explorer 4.0 or later 



v 



Each choice above gives smaller Web pages than the choice before 



Options 



I I Allow PNG as a graphics format 

^] Rely on VML for displaying graphics in browsers 

HI Save an additional version of the presentation for older browsers 



□ Save new Web pages as Single File Web Pages 



OK 



Cancel 



Figure 14-12: Using PowerPoint's browser tab in the Web Options dialog 
box. 



You're also presented with options for saving graphics in Portable Network Graphics 
(PNG) format, and saving line art as Vector Markup Language (VML). Again, these 
should only be checked if you know your target audience's browsers support these 
formats. You can be sure that older versions of Netscape don't support PNG, and 
that the only browser that supports VML is Internet Explorer. PNG is a bitmap 
graphics format similar to GIF but capable of a much deeper range of colors. VML is 
an XML-based markup language for vector graphics, which are geometry-based 
graphics based on a Cartesian-like grid system similar to what you'll find in CAD 
programs and applications such as Adobe Illustrator or Macromedia Freehand. A 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 247 



long time ago, VML competed with Scalable Vector Graphics Language (SVG) as a 
standard, but the W3C chose SVG, which is also covered briefly in this chapter. 

This tab has two additional options that are pretty self explanatory: Save an 
additional version of this presentation for older browsers and Save new Web pages 
as Single File Web Pages. 

Changing settings in the Files tab 

In the Files tab (shown in Figure 14-13) you can organize supporting files in a folder 
or store them within the presentation folder itself. The reference to long file names 
dates back to the old 8.3 DOS conventions, when file names were limited to eight 
characters and didn't allow for spaces. 



Web Options 



General 



Browsers 



Files 



Pictures 



Encoding 



Fonts 



File names and locations - 

•] Organize supporting files in a folder 
Use [ong file names whenever possible 
•] Update links on save 

Default editor 



Check if Office is the default editor for Web pages created in Office 



OK 



Cancel 



Figure 14-13: Changing settings in the Files tab. 



If you choose the option Check if Office is the default editor for Web pages created in 
Office, you can edit the PowerPoint HTML presentation in PowerPoint itself rather 
than your system's default Web editor. This just means that PowerPoint will treat the 
file like any other PowerPoint presentation, providing you with all of PowerPoint's 
tools within its user interface. In other words, it's like opening up a PowerPoint 
presentation. 



Choosing screen resolution in the Pictures tab 

This one is pretty self-explanatory. The Pictures tab has one option, which allows 
you to choose the screen resolution. The most common screen resolution for most 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



248 PartM ♦ HTML/XHTML Authoring Fundamentals 



Web interfaces is 800 x 600 (pixels), so that's a good one to choose if you're 
targeting a large cross-browser audience. 

Choosing an encoding in the Encoding tab 

The default on the Encoding tab (shown in Figure 14-14) is a Windows encoding, not 
necessarily what you want. Encodings are tricky, but simple at their core. Each letter 
in an alphabet, be it an English, Japanese, or Russian alphabet, is mapped to a 
special numeric value (after all, computers can't read — they deal with binary sets of 
numbers only at their core level). The problem is not all such mappings, called 
encodings, are the same. If you choose a Windows encoding, which was created 
before more standardized encodings were approved by international bodies, the 
potential exists that visitors to your Web site will get some funny characters. To 
eliminate this potential, change the default setting to Western European, as shown in 
Figure 14-14. 



Web Options 



General Browsers Files Pictures Encoding Fonts 



Encoding 
Reload the current document as: 



Save this document as: 



iWestern European (ISO) 



Zl Always save Web pages in the default encoding 



OK 



Cancel 



Figure 14-14: You should change the default encoding to a more Web- 
standardized one. 



Using the Fonts tab to choose fonts 

The Fonts tab allows you to use the default font character set, as well as a default 
proportional and fixed-width typestyle along with their point sizes. After clicking OK, 
you then click Publish to save your document. 

Listing 14-2 shows how an HTML page generated by PowerPoint looks. Note the use 
of the many namespaces as represented by the xml ns namespace declarations (they 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 249 



look like attributes, but they're actually namespace declarations that bind elements 
to a specific type of application, in this case, MS Office). 



Listing 14-2: Under the Hood of a PowerPoint Web 
Page Export 

<html xmlns:v="urn:schemas-microsoft-com:vml" 
xmlns:o="urn:schemas-microsoft-com:office:office" 
xmlns:p="urn:schemas-microsoft-com:office:powerpoint" 
xmlns:oa="urn:schemas-microsoft-com:offlce:activation" 
xmlns="http: //www. w3.org/TR/REC -html 40 "> 




<head> 

<meta http-equi v=Conten 

<meta name=ProgId conte 

<meta name=Generator co 

< 1 ink r e 1 = F i 1 e - L i s t 

href="The%20Miraculous5S 

< 1 ink rel=Previ ew 

href="The%20MiraculousZ 

< 1 ink rel=Edit-Time-Dat 

href="The%20Miraculous% 

<title>The Miraculous S 

<!--[if gte mso 9]><xml 

<o:DocumentProperties> 

<o : Author>Chuck White 

<o:Template>OCEAN</o: 

<o : LastAuthor>Chuck W 

<o:Revision>3</o:Revi 

<o:TotalTime>18</o:To 

<o:Created>2003-ll-02 

<o: LastSaved>2003-ll- 

<o:Words>24</o:Words> 

<o: Presentation Format 

<o : Company>The Tumeri 

<o:Bytes>62053</o:Byt 

<o:Paragraphs>6</o:Pa 

<o:Slides>2</o:Slides 

<o:Version>11.4920</o 

</o:DocumentPropertie 

<o:OfflceDocumentSetti 

<o:PixelsPerInch>80< 

</o:0fficeDocumentSett 

</xml><![endif]--> 

< 1 ink rel=Presentati on - 

href="The%20MiraculousZ 

<meta name=Descri pti on 

SI i deshow") 

<meta http-equi v=expi re 
<![if !ppt]Xscript> 



t-Type content="text/html ; cha rset=i so -8859- 1' 

nt=PowerPoint.Sl ide> 

ntent="Mi crosof t PowerPoint 11"> 

20S1 i deshow_fll es/fil el i st . xml "> 

20S1 i deshow_fll es/preview.wmf"> 

a 

20S1 idesho w_fi les/editdata.mso"> 

1 i deshow</t i tl e> 



</o : Author) 

Tempi ate> 

hite</o:LastAuthor> 

s i o n > 

tal Time) 

T03:43:46Z</o:Created> 

02T04:02:44Z</o:LastSaved> 

>0n-screen Show</o:PresentationFormat) 

c Partnershi p</o : Company) 

es> 

ragraphs) 

> 

: V e r s i o n > 

s> 

ngs> 

/o:PixelsPerInch> 

i n g s > 

XML 

20S1 idesho w_fi les/pres.xml "> 

content="ll/l/2003: The Miraculous 

s content=0> 



Continued 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



250 PartM ♦ HTML/XHTML Authoring Fundamentals 



Listing 14-2: (continued) 



var ver = 0, appVer = navi gator . appVersi on , msie = 
appVer . i ndexOf ( "MSIE " ) 

var msieWin31 = ( appVer . i ndexOf( "Windows 3.1" ) >= 0), 
isMac = ( appVer . i ndex0f( "Maci ntosh" ) >= 0) 
if( msie >= ) 

ver = parseFloat( appVer . substri ng( msie+5, 
appVer. indexOf ( ";", msie ) ) ) 
el se 

ver = parselnt( appVer ) 

if( lisMac && ver >= 4 && msie >= ) 
window.location.replace( 
"The%20Miraculous^20Sli deshow_fil es/frame.htm"+document.locat 
i o n . h a s h ) 

else i f ( ver >= 3 ) { 
var path = 
"The%20Miraculous^20Sli deshow_fil es/v3_document .htm" 

if ( ImsieWin31 && ( ( msie >= && ver >= 3.02 ) 
|| ( msie < && ver >= 3 ) ) ) 

window.location.replace( path ) 
el se 

window. location. href = path 
1 

</script><! [ e n d i f ] > 
</head> 

</html> 



Exporting OpenOffice.org presentations 

OpenOffice (www .openofflce.org)is a free office suite that can read and write MS 
Office documents such as Word and PowerPoint. So, if you don't want to spend 
money for PowerPoint, you don't have to. OpenOffice is almost as good, and it's free. 

The first step to exporting an OpenOffice presentation to the Web is to select File O 
Export from the main menu. You'll then be presented with a wizard, as shown in 
Figure 14-15. 

You can choose an existing design or create a new one. This can be somewhat 
confusing because the natural assumption is that you've already created your design 
in the slide presentation program, so why is OpenOffice asking you to create a new 
one? When you click Next, you find out what the application is referring to. What you 
are doing is deciding how you want the HTML to work. Do you want frames? Or, do 
you prefer to avoid frames? Those options are the first two listed in the wizard's 
radio buttons under the label "Publication type." You can then choose whether or 
not to create a title page or notes for the online version of your presentation. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 251 



HTML Export 



O^ 



Assign design 




(~ New design 
* iExisting Desijgni 



Delete Selected Design 



Select an existing design or create a new one 



Help 



Cancel 



<< Back 



Next >> 



Create 



Figure 14-15: The OpenOffice HTML Export wizard. 

The next two "Publication type" options are Automatic and Webcast. If you choose 
Automatic, the wizard changes its appearance, as shown in Figure 14-16. 

The wizard changes labels from Options to Advance slide. You can allow the user to 
advance the slide herself by choosing the As stated in document radio button, or 
create an automated page that moves to the next slide automatically at a named 
interval by choosing the Automatic radio button. 

If you choose the Webcast publication type, the wizard changes again, to a screen 
that looks like that shown in Figure 14-17. 

You're then presented with the option of generating server-side script for Active 
Server Pages or by using Perl. When you choose this option, OpenOffice generates a 
series of Perl scripts for managing the slideshow. 

The rest of the options in the HTML Export wizard are pretty self-explanatory. They 
allow you to choose what kind of buttons you want to include (if you've chosen to 
generate static HTML instead of a Webcast or server-side script), what resolution 
you want OpenOffice to process images, and so on. 



SMIL 



The Synchronized Multimedia Language (SMIL, pronounced like the word smile) is 
an XML-based language for presenting multimedia programs over the Web. You can 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 



8:48 



252 PartM ♦ HTML/XHTML Authoring Fundamentals 



I HTML Euport 




Publication type — 

C Standard HTML format 

C Standard HTML with frames 

(• [Automatic: 



C WebCast 




Help 



Cancel 



Advance slides — 
(• As stated in document 

C Automatic 

Slide view time: 1 00:00: 1 5 

|7 Endless 



<< Back 



Next >> 



1 



Create 



Figure 14-16: The HTML Export wizard changes its appearance depending on the 
Publication type you choose. 



HTML Export 



Publication type — 

C Standard HTML format 
f* Standard HTML with frames 
C Automatic 
P WebCast 






WebCast — 
(• Active Server Pages (ASP) 

O Perl 

URL for listeners 



jyindex.html 
URL for presentation: 



URL for Perl scripts: 



*l 




Help 



Cancel 



<< Back 



iNext >>: 



Create 



Figure 14-17: The HTML Export Wizard displays server-side scripting options when you 
choose Webcast. 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 253 



use it to create slide shows, or as a presentation layer for media players such as 
RealOne or QuickTime (but not for Windows Media Player). You can hand code a 
SMIL document, keeping in mind XML syntax rules (closing all elements, nesting tags 
within one root element, quoting all attribute values, and so on). To create a SMIL 
presentation, follow these basic steps. 

1. A source begins and ends with the smi 1 element. SMIL is a case-sensitive 
language and always uses lowercase: 

<smi 1 > 

[...] 

</smil> 

2. SMIL documents consist of two parts, a head and body, both of which must live 
within the smi 1 element, which is a parent element of the head and body 
elements. 

<smi 1 > 

<head> 

[...] 

</head> 

<body> 

[...] 

</body> 
</smil> 

3. You can also include meta tags in the head element, but you need to remember 
that because SMIL is based on XML, the element must include its closing 

tag: 

<meta name="descri pti on" content="A great show!" /> 

4. Next, you need to include some layout elements, within which will go the most 
important pieces of your multimedia show. The following code shows where to 
put the layout elements (in bold). 

<smi 1 > 
<head> 

<meta name="descri ption" content="A great show!" /> 

<1 ayout> 
<! - - 1 ayout tags - -> 

</l ayout> 
</head> 
<body> 

<!-- media and synchronization tags --> 
</body> 
</smil> 

5. You'll need to determine the screen size of your presentation. You do this with 
the root - 1 ayout element, which includes width and height attributes to 
determine the width and height that the media player, such as QuickTime or 
RealOne, should allot to its window size: 

<root-layout width="300" height="200" 

background-col or="white" /> 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



254 PartM ♦ HTML/XHTML Authoring Fundamentals 



6. You can also use absolute positioning to position elements within the media 
player's screen. Absolute positioning in SMIL uses the same concepts as 
absolute positioning in Cascading Style Sheets, with a grid whose point of 
origin is the upper-left corner, which is pixels. The following code fragment 
creates a region, which is simply a container for holding elements similar to 
HTML's di v element. The region begins 20 pixels from the left-most portion of 
the media player's window, and 20 pixels from the top. 

<head> 
<1 ayout> 
<root-layout width="300" hei ght="200" 

background-col or="white" /> 
<region id="regionl" left="20" top="20" 
width="100" height="200" /> 
</l ayout> 
</head> 

Note that the region has also been given a width and a height. Now you are able 
to create elements and include them within this region. 




See Chapter 23 for details on how absolute positioning works. 



7. The first element we'll drop into our new region is a logo, which was created in 
Adobe Illustrator and exported as SVG. Note that you can create an SVG image 
in OpenOffice. org's drawing module if you don't want to pay the licensing 
fees for Adobe Illustrator. Including the SVG in the document is as easy as 
writing an HTML i mg element: 

<body> 

<img src="l ogo. svg" al t="Javerti sing! " 
regi on="l ogo" /> 
</body> 

Note that you must identify in which region to place the logo. The following 
code creates a new region named logo for holding the logo. 

< s m i 1 > 
<head> 
<1 ayout> 
<root-layout width="300" hei ght="200" 

background-col or="white" /> 
<region i d="l ogo" left="20" top="20" 

width="100" hei ght="100" background-col or="white" 
/> 

</l ayout> 
</head> 
<body> 
<img src="l ogo. svg" al t="Javerti sing! " 
regi on="l ogo" /> 
</body> 
</smil> 

8. Next, save the file with a . smi 1 file extension, then open it in an 
SMIL-compliant media player such as RealOne or QuickTime. 



PI: JYS 

WY022-14 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



Chapter 14 ♦ Multimedia 255 



9. The resulting presentation is shown in Figure 14-18. You can put any number of 
media objects in place of that SVG file, such as videos and even text. 



<j) RealOne Player 
smite 



File Edt Veiy Pa^ FewHtes TdoIs he^ IF3I 




W| 



(>>o®s* 



ft 'Hone '! 5C.I fjljl ■¥•'' address httpiA'tane. reel. ccnv"? 



RealOne GUIDE 



ISLPEF.FASS TODAY 

[►LKbwPlajJng |l(^Web $£3 My Linraty 0* CD £J Davlce; fl^ Radio (£J Channels '-'.1, Search 




Figure 14-18: A simple SMIL-based presentation shown in RealOne. 



Naturally, you're not limited to SVG; in fact, that particular graphics format has not 
yet really taken hold, although it still holds great promise. It's more likely you'll use a 
JPEG or GIF graphic, along with some video and/or audio. Table 14-3 shows the kinds 
of media you can use in a SMIL document and the support from the major SMIL 
media players. You may not have heard of GRiNS. GRiNS is a media player from 
Oratrix that you can find at http: //www. oratrix.com/Products/G2 P. 



Table 14-3 
Multimedia Player Support for Media 


Content Using SMIL 


Media Tag 


RealOne 


QuickTime 


CriNS 


GIF img 


Yes 


Yes 


Yes 


JPEG img 


Yes 


Yes 


Yes 


SVG img 


Yes 


No 


No 



Continued 



PI: JYS 
WY022-14 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:48 



256 PartM ♦ HTML/XHTML Authoring Fundamentals 



Table 14-3 (continued) 


Media Tag 


RealOne 


QuickTime 


CriNS 


Microsoft Wav audio 


Yes 


Yes 


Yes 


Sun Audio audio 


Yes 


Yes 


Yes 


Sun Audio Zipped audio 


No 


Yes 


No 


MP3 audio 


Yes 


Yes 


No 


Plain text 


Yes 


Yes 


Yes 


Real text textstream 


Yes 


No 


No 


Real movie video 


Yes 


No 


No 


AVI video 


Yes 


No 


Yes 


MPEG video 


Yes 


No 


Yes 


MOV video 


Yes 


No 


No 



You've seen how to construct a basic SMIL document, and how anyone with a simple 
text editor can create a presentation or show. There's much more to SMIL than this, 
including more advanced functionality, such as media sound and video 
synchronization. To read more about how you can create lavish rich media using 
SMIL, visit the W3C SMIL Web site at: http://www.w3.Org/AudioVideo/.Or.visit 
a SMIL tutorial at http: //www . w3school s.com/smil/smil_reference.asp. 



Summary 



In this chapter, you learned about the following multimedia topics: 

4 Introducing multimedia objects 

4 Multimedia plug-ins and players 

4 Animations 

4 Video clips 

4 Sounds 

4 Slide shows 



You were also warned that you should use multimedia with care. The most practical 
use for multimedia is often the simple slide show, because the demands for 
professionalism won't be quite as stringent. But if you dabble in such multimedia 
formats as Flash and video, be sure to keep a close eye on quality, because a poorly 
developed multimedia presentation is worse than none at all. 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



Scripts 



Standard HTML was designed to provide static, text-only 
documents. No innate intelligence is built into plain 
HTML, but it is desired, especially in more complex documents 
or documents designed to be interactive. Enter scripts — svelte 
programming languages designed to accomplish simple tasks 
while adhering to the basic premise of the Web; easily 
deployable content that can play nicely with plain-text HTML. 

This chapter covers the basics of scripting and goes into the 
details of how to use client-side scripting in your documents. 



Client-Side versus Server-Side 



Scripting 



There are two basic varieties of scripting, client-side and 
server-side. As their names imply, the main difference is where 
the scripts are actually executed. 



Client-side scripting 



Client-side scripts are run by the client software — that is, the 
user agent. As such, they impose no additional load on the 
server, but the client must support the scripting language 
being used. 

JavaScript is the most popular client-side scripting language, 
but Jscript and VBScript are also widely used. Client-side 
scripts are typically embedded in HTML documents and 
deployed to the client. As such, the client user can usually 
easily view the scripts. 

For security reasons, client-side scripts generally cannot read 
or write to the server or client file system. 



Client-Side versus 
Server-Side Scripting 




Setting the Default Scripting 
Language 

Including a Script 

Calling an External Script 

Triggering Scripts with 
Events 

Hiding Scripts from Older 
Browsers 



Server-side scripting 



Server-side scripts are run by the Web server. Typically, these 
scripts are referred to as CGI scripts, CGI being an acronym for 




257 



PI: JYS 

WY022-15 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



258 PartM ♦ HTML/XHTML Authoring Fundamentals 



Common Gateway Interface, the first interface for server-side Web scripting. 
Server-side scripts impose more load on the server, but generally don't influence the 
client — even output to the client is optional; the client may have no idea that the 
server is running a script. 

Perl, Python, PHP, and Java are all examples of server-side scripting languages. The 
script typically resides only on the server, but is called by code in the HTML 
document. 

Although server-side scripts cannot read or write to the client's file system, they 
usually have some access to the server's file system. As such, it is important that the 
system administrator take appropriate measures to secure server-side scripts and 
limit their access. 

Note Unless you are a system administrator on the Web server you use to deploy 

your content, your ability to use server-side scripts is probably limited. Your ISP 
or system administrator has policies that allow or disallow server-side scripting 
in various languages and performing various tasks. 

If you intend to use server-side scripts, you should check with your ISP or system 
administrator to determine what resources are available to you. 

This chapter deals with client-side scripting. 

Cross- Wl For more information on server-side scripting, see Chapter 28. 
Reference 




Setting the Default Scripting Language 

To embed a client-side script in your document you use the <scri pt> tag. This tag 
has the following, minimal format: 

<script type=" scri pt_type"> 

The value of scri pt_type depends on the scripting language you are using. The 
following are generally used script types: 

♦ text/ecmascri pt 

♦ text/ javascri pt 
4 text/ jscri pt 

4 text/vbscri pt 
4 text/vbs 
4 text/xml 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



Chapter 15 ♦ Scripts 259 



Note 



For example, if you are using JavaScript, your script tag would resemble the 
following: 

<script type=" text/ javascript") 

The W3C recommends that you specify the default script type using an appro- 
priate META tag in your document. Such a tag resembles the following: 

<META http -equ i v=" Content- Sen' pt- Type" 
content=" text/ Java script") 

Note that this does not alleviate the need for the type attribute in each 
<script> tag. You must still specify each <script> tag's type in order for 
your documents to validate against HTML 4.01. 

If your script is encoded in another character set than the rest of the document, you 
should also use the cha rset attribute to specify the script's encoding. This 
attribute has the same format as the cha rset attribute for other tags: 

cha rset=" char a cter_encodi ng_type" 



Including a Script 



To include a script in your document, you place the script's code within <scri pt> 
tags. For example, consider the following script: 

<script type=" text/ javascript") 
function NewWi ndow( url ) { 

fin=wi ndow. open( url , "" , "width=800 , hei ght=600 , 
scrollbars=yes,resizabl e=yes" ) ; 
I 
</script> 

You can include as much scripting code between the tags as needed, providing that 
the script is syntactically sound. Scripts can be included within the <head> or 
<body> sections of a document, and you can include as many <scri pt> sections as 
you like. Note, however, that nested < s c r i pt > tags are not valid HTML. 

Generally, you will want to place your scripts in the < h e a d > section of your 
document so the scripts are available as the rest of the page loads. However, you 
may occasionally want to embed a script in a particular location in the document — in 
those cases, place an appropriate <scri pt> tag in the <body> of the document. 



Calling an External Script 



If you have some scripts that you want to use in multiple documents, consider 
placing the scripts in an external file. You can then use the s re attribute of the 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



260 PartM ♦ HTML/XHTML Authoring Fundamentals 



<scri pt> tag to specify that the script content can be found in that file. For 
example, suppose you want to include the following script in multiple documents: 

function NewWindow(url)! 

fln=window.open(url,"","width=800,height=600, 
scnollbans=yes,resizable=yes"); 



You can place the script in a text file on the server and specify the file's URL in the 
appropriate <scri pt> tags' s re attribute. For example, suppose the preceding file 
was stored in the file sen' pts . j s on the server. Your script tag would then 
resemble the following: 

<scnipt typ e=" text/ j a vase nipt" snc="scnipts.js"X/scnipt> 

One major advantage to external script files is that if you need to edit the script, you 
can edit it in one place — the external file — and the change is effected in all the files 
that include it. 



Triggering Scripts with Events 



Most HTML tags include several event attributes that can be used to trigger scripts. 
Table 15-1 lists these attributes and their use for triggering scripts. 




Cross- See Appendix A for a comprehensive list of what tags support event attributes. 

Reference 



Table 15-1 
Event Attributes 


Attribute 


Trigger Use 


Onclick 


When item(s) enclosed in tag is clicked 


Ondblclick 


When item(s) enclosed in tag is double-clicked 


Onmousedown 


When mouse button is pressed while mouse pointer is over item(s) 
enclosed in tag 


Onmouseup 


When mouse button is released while mouse pointer is over item(s) 
enclosed in tag 


Onmouseover 


When mouse pointer is placed over the item(s) enclosed in tag 


Onmousemove 


When mouse is moved within the item(s) enclosed in tag 


Onmouseout 


When mouse is moved outside of the item(s) enclosed in tag 



Onblur 



When item(s) enclosed in tag have focus removed 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



Chapter 15 ♦ Scripts 261 



Attribute 


Trigger Use 


Onfocus 


When item(s) enclosed in tag receive focus 


Onload 


When the document finishes loading (valid only in <body> tag) 



Onunload When the document is unloaded— when the user navigates to another 

document (valid only in <body> tag). This event is often used to create 
pop-ups when a user leaves a site 

Onsubmit When a form has its submit button pressed (valid only in <f orm> tags) 

Onreset When a form has its reset button pressed (valid only in <f orm> tags) 

Onkeypress When a key is pressed while the mouse pointer is over the item(s) 

enclosed in the tag 

Onkeydown When a key is pressed down while the mouse pointer is over the item(s) 

enclosed in the tag 

Onkeyup When a key is released while the mouse pointer is over the item(s) 

enclosed in the tag 



Note 



Many of the event attribute triggers are dependent on the element(s) to which 
they apply being "in focus" at the time of the trigger. For example, in an HTML 
form an onmouseout event attached to one field will not trigger unless the 
same field has the focus. 

Event triggers have a variety of uses, including the following: 

♦ Form data verification 

Using onfocus and onbl ur attributes, each field can be verified as it is edited. 
Using onsubmi t and onreset, an entire form can be verified or reset when the 
appropriate button is clicked 

♦ Image animation 

Using onmouseover and onmouseout attributes, an image can be animated 
when the mouse pointer passes over it 

♦ Mouse navigation 

Using onclick and ondbl cl i ck attributes, you can trigger user agent 
navigation when a user clicks or double-clicks an element 

For example, you can create images to use as buttons on your page. Figure 15-1 
shows two images for use on a button. The image on the left is used for general 
display, while the image on the right is used when the mouse is over the button. 



T 'P Users appreciate visible feedback from elements on your page. As such, it is im- 

\, portant to always provide visible changes to navigation elements— links should 

have a visibly different style when moused over, as should navigation buttons. 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



262 PartM ♦ HTML/XHTML Authoring Fundamentals 



^ Jasc Paint Shop Pro - home-off 



. -i - 



File Edit View Image Effects Colore Layeis Ohjects Selections Masks 
Window Help 



D^Qi| & % m \&®\[]^s\mMfh 




For Helpj press Fl 



|lmage: 150 x 50 x 16 Million - 22, 1 KBytes 



Figure 15-1: Two images for use as a button. 



Combining onmouseover, onmouseout, and onclick events, you can easily create 
a button that reacts when the mouse is over it and navigate to a new page when 
clicked. Consider the following document that uses a few JavaScript scripts and 
events to create a navigation button. 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<META http-equiv=" Content -Script -Type" 

content=" text/ javascript") 

<title>Event Buttons</ti tl e> 

<script type="text/javascript"> 
// Activate the specified button 
function acti vate( bname ) { 
image id = bname + "button"; 
aname = bname + "-on.jpg"; 
document. images(i mage id).src = 
aname ; 



// Deactivate the spec i fled button 
function deacti vate ( bname ) 1 

imageid = bname + "button"; 

dname = bname + "-off.jpg"; 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



Chapter 15 ♦ Scripts 263 



document. images( image id) .src = 
dname ; 
) 
</script> 

</head> 
<body> 

<P> 

<img alt="Home page" i d="homebutton" 

src="home -off . jpg" 

onmouseover="activate( 'home' )" 

onmouseout="deactivate( 'home' )" 

onclick=" document. location='home. html'" 
> 

</p> 
</f onm> 
</body> 
</html> 

When the document loads, the button is displayed in its inactive (off) state, as 
shown in Figure 15-2. When the mouse is placed over the button, the onmouseover 
event launches the JavaScript acti vate function and the button is displayed as 
active (on), as shown in Figure 15-3. 



g] http://localhostChapter15.'hiittonsamp.htiril - ... SOB 



File Edit View Favorites Tools Help 



Address ^ http://localhost/Chapterl5/buttonsamp, html v. gj Go 



% 






\4 Local intranet 



Figure 15-2: The button is initially displayed in its 
inactive (off) state. 



When the mouse leaves the button, the onmouseout event launches the 
deactivate function, returning the button display to its inactive state. When the 
button is clicked, the onclick event changes the 1 ocati on property of the user 
agent, effectively navigating to a new page (in this case home . html ). Note that the 



PI: JYS 

WY022-15 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



264 PartM ♦ HTML/XHTML Authoring Fundamentals 



gj http://localhost^Chapter15/buttoiisamp.html - ... BBS' 



File Edit View Favorites Tools Help 



o ■••* g - a i <s I p ft *■ © | a - ' 

Address @ http://localho5t/Chapterl5/button5amp.htrnl v] fl Go 



Horn 



I 



|Home page| 






*£J Local ii 



Figure 15-3: The button is changed to active (on) 
when the mouse is over it. 



JavaScript code for the onclick attribute is contained directly in the value of the 
attribute — because the code is only one line a separate function is not necessary. 




Cross- \ JavaScript is covered in more detail in Chapter 25. 
Reference 



Hiding Scripts from Older Browsers 



Not all browsers support JavaScript. Many of the older browsers are not JavaScript 
enabled, and some of the latest browsers may not support the scripting language 
you are using. 



Note 



Most modern browsers will ignore scripts of types they do not recognize. 



If you are concerned about older browsers not recognizing your scripts, you will 
need to hide your scripts so that older browsers will ignore them (instead of trying 
to render them). 

To hide your scripts, simply place them within a special set of comment tags. The 
only difference between normal comment tags and script-hiding tags is that the 
closing tag contains two slashes (/ /). Those two slashes enable browsers that 
support scripting to find the script. 



PI: JYS 
WY022-15 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



Chapter 15 ♦ Scripts 265 



For example, the following structure will effectively hide the scripts within the 
<scri pt> tag: 

<script type=" text/ javascript") 

<!-- hide scripts from older browsers 

— Script content — 

// stop hiding scripts - - > 
</script> 



Summary 



This chapter introduced how to add basic intelligence and dynamic content to your 
site view client-side scripting. You learned how to embed scripts in your documents 
and how to utilize external script files. You also learned how to use event attributes 
to trigger scripts from user actions. 

Chapters 25 through 28 provide additional scripting content. 

♦ ♦ ♦ 



PI: JYS 

WY022-15 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 13:21 



266 



P1:FRU 

WY022-16 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



Controlling 
Presentation 
with CSS 










Chapter 16 

Introducing 
Cascading Style 
Sheets 

Chapter 17 

Creating Style 
Rules 

Chapter 18 

Fonts 

Chapter 19 

Text Formatting 

Chapter 20 

Padding, 
Margins, and 
Borders 

Chapter 21 

Colors and 
Backgrounds 

Chapter 22 

Tables 

Chapter 23 

Element 
Positioning 

Chapter 24 

Defining Pages 
for Printing 




267 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 




268 



P1:FRU 

WY022-16 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



Introducing 
Cascading 
Style Sheets 



The first part of this book emphasized the importance of 
Cascading Style Sheets (CSS) and the standards migration 
away from hardcoded HTML and toward using styles. This 
part of the book, starting with Chapter 16, delves deeply into 
the subject of CSS. 

This chapter provides an overview of what CSS is, and the next 
few chapters cover details about various formatting property 
groups and how to best use them. 



CSS Overview 

Cascading Style Sheets were created to provide a powerful, yet 
flexible means for formatting HTML content. CSS works much 
like style sheets in a word processing program — you define a 
"style" that contains formatting options that can be applied to 
document elements. 

For example, consider the following code: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>A Sample Styl e</ti tl e> 

<style type="text/css"> 
hi I color: Red ; 1 

</style> 
</head> 
<body> 



Note the <styl e> element inside of the <head> element. It 
defines one style, setting the font color of all < h 1 > elements 




♦ ♦ ♦ ♦ 
In This Chapter 

CSS Overview 

Style Rules 

Style Rule Locations 

Understanding the Style 
Sheet Cascade 

The CSS Box Formatting 
Model 

CSS Levels 1 , 2, and 3 

♦ ♦ ♦ ♦ 




269 



P1:FRU 

WY022-16 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



270 Part III ♦ Controlling Presentation with CSS 



to red. This is the same as using the following code throughout the document, 
wherever <hl> elements are used: 

<hl><font col or="red">Headi ng Text</f ont></hl> 

Using the preceding method (<f ont> tags), you would need to change every 
instance in the document if you later changed your mind about the formatting. Using 
CSS requires that you change only the style definition at the top of the document to 
affect all < h 1 > elements. 

Note CSS can be a complicated beast, especially once you get into the different 

selector methods, inheritance, and the complete cascade picture. However, at 
its core it is a very simple concept: Assign formatting attributes in one place that 
can be easily modified later. As you read through the chapters in Part II, keep 
this concept in mind and resist getting bogged down in the CSS concepts that 
you may not need. 



Style Rules 

All style rules follow the same basic format: 



selector { propertyl: valuel; property?: valueZ; ... 
propertyN: valueN; I 

Note that the formatting of CSS rules is very exact and follows these guidelines: 

♦ The selector is followed by the formatting property definitions, which are 
enclosed in braces ({ }). 

♦ A colon separates each property/value pair. Note that values that include 
spaces should be enclosed in double quotes, as in the following example: 

font-family: "Times New Roman"; 

♦ Each property/value pair ends with a semicolon. 

T 'P Technically, the last property/value pair of a style definition need not end in 

a semicolon. However, it is good practice to end all your property/value pairs 
y with a semicolon. 

The selector is the elements that the style should be used on. The properties are all 
formatting properties of the selected elements that should be set to the associated 
values. A very simple example of a style rule follows: 

hi 1 color: Red ; 1 

The selector (h 1) causes this rule to be applied to all < h 1 > elements. The color 
property affects the font color of matching elements — in this case, the font color is 
set to red. 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



Chapter 16 ♦ Introducing Cascading Style Sheets 271 



You can specify multiple selectors to apply to the same style definition — you 
separate the selectors with commas. For example, if you wanted all heading tags 
(1 through 6) to render as red text, you could use the following definition: 

hi, h2, h3, h4, h5, h6 { color: red; I 




Cross- 
Reference 



Selectors are covered in detail in Chapter 17. 



Style Rule Locations 



Styles can be defined within your HTML documents or in a separate, external style 
sheet. You can also use both methods within the same document. The following 
sections cover the various methods of defining styles. 



Using the <style> element 



The <sty 1 e> element behaves like other HTML elements. It has a beginning and 
ending tag and everything in between is treated as a style definition. As such, 
everything between the <styl e> tags needs to follow style definition guidelines. A 
document's < s ty 1 e > section must appear inside the document's < h e a d > section, 
although multiple <styl e> sections are permissible. 

The <sty 1 e> tag has the following, minimal format: 

<style type="text/css"> 
... styl e defini ti ons . . . 
</style> 



External style sheets 



You can also place your style definitions in a separate file and reference that file 
within the documents where you need it. When creating a separate style sheet file, 
you do not need to include the <sty 1 e> tags, only the definitions. For example, the 
following is an example style sheet file named my styl es . ess: 



/* 


mystyl es . ess 


- Styles for the main 


site * 


hi 


h2, h3, h4 


{ col or : blue; ) 




hi 


{ f o n t - s i z e : 


18pt 


} 




h2 


{ f o n t - s i z e : 


16pt 


) 




h3 


{ f o n t - s i z e : 


14pt 


) 




h4 


{ f o n t - s i z e : 


12pt 


} 




P 


f o n t - s i z e : 


lOpt; 


) 





T 'P You can include comments in your styles to further annotate your definitions. 

Style comments begin with a /*and end with a */. Comments can span several 
lines, if necessary. 



P1:FRU 

WY022-16 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



272 Part III ♦ Controlling Presentation with CSS 



To link an external style sheet with a document, use the <1 i n k> tag in the <head> of 
the document to which you want the styles applied. The <1 i n k> tag has the 
following format when used to link a style sheet: 

< 1 ink rel="styl esheet " type="text/css" 
href="url_to_styl e_sheet" /> 

Continuing with the my sty 1 es . ess style sheet example, the following <1 i n k> tag 
would link the style sheet to the document: 

<head> 

< 1 ink rel ="styl esheet" type="text/css" 

href="mystyl es . ess" /> 
</head> 

T 'P Although external style sheets can have any valid filename, it is advisable to 

name your style sheets with an extension such as . ess to easily identify what 
' the file contains. 

You can use the < 1 i n k> tag to link any style sheet that is accessible to the user via 
HTTP. If your style sheet was on another server, for example, you would simply 
include a full form URL to the sheet: 

< 1 ink rel="styl esheet " type="text/css" 
href="http: //www. example. com/styles/sales. ess" /> 

Several style sheets can be linked to the same document. When that is the case they 
follow the cascading guidelines as covered in the section Understanding the style 
sheet cascade later in this chapter. 

Style definitions within individual tags 

Most HTML tags include a styl e attribute that allows you to specify styles that 
should directly impact the tag in which they appear. For example, if you wanted a 
particular < h 1 > tag to render its text in red, you could use the following code: 

<hl styl e="col or : red;">Red Headl i ne</hl> 

The only advantage to using styles in this manner is to remain HTML 4.01 compliant. 
It is a much better practice to put your styles in a <styl e> tag or external style 
sheet than to code individual tags. However, sometimes you might find that nudging 
a particular tag individually is advantageous. 

Understanding the Style Sheet Cascade 

The concept behind Cascading Style Sheets is essentially that multiple style 
definitions can trickle, or cascade, down through several layers to affect a document. 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



Chapter 16 ♦ Introducing Cascading Style Sheets 273 



Several layers of style definitions can apply to any document. Those layers are 
applied in the following order: 

1. The user agent settings (typically, the user is able to modify some of these 
settings) 

2. Any linked style sheets 

3. Any styles present in a <sty 1 e> element 

4. Styles specified within a tag's sty 1 e attribute 

Each level of styles overrides the previous level where there are duplicate properties 
being defined. For example, consider the following two files: 



mystyl es .ess 



/* mystyles 



hi, 

hi 

h2 

h3 

h4 

P ( 



h2. h3, 
f o n t - s i 
f o n t - s i 
f o n t - s i 

f o n t - s i z e 
f o n t - s i z e : 



CSS 

h4 
ze : 
ze : 
ze : 



- Styles for the main site */ 
{ col or : blue; 1 
18pt; 1 
16pt; 1 

14pt; I 
12pt; I 
lOpt; 1 



i ndex. html 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<link rel ="styl esheet" type="text/css" 
href="mystyl es . ess" /> 

<style type="text/css"> 
hi 1 color: Red ; 1 

</style> 
</head> 
<body> 

<hl> A Sample Heading</hl> 



Note 



What color will the <hl> heading in i ndex . html be? The external style specifies 
blue, but the style element specifies red. In this case, the internal style takes 
precedence and the < h 1 > text will appear in red. 

One advantage to cascading is that documents at different levels or from dif- 
ferent departments can be similar, but have a slightly different look or feel 
to match their origin. For example, you could have a company, ess style 
sheet that is linked to all corporate documents. You could also have an hr- 
department.css style sheet that adds additional definitions or replaces some 
of the standard corporate definitions to give HR documents a slightly different 
look and feel. 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



274 Part III ♦ Controlling Presentation with CSS 



In addition, a document may have multiple instances of linked style sheets or 
<sty 1 e> elements. In such cases, the sheets are applied in order, with subsequent 
definitions overriding any previous definitions. 

Note that properties are only overridden when they appear multiple times. 
Otherwise, the styles are additive. For example, the text in the < h 1 > tag would still 
be rendered in 18pt type (from the external definition); only the color would 
change. 



The CSS Box Formatting Model 



CSS uses a clever metaphor for helping you specify containers (block-level elements) 
on your page: the box. When you define formatting for your block-level 
elements — whether they be paragraphs, blockquotes, lists, images, or whatever — for 
purposes of CSS, you are defining formatting for a box. CSS doesn't care what is in 
the box; it just wants to format the box. 



Box dimensions 

The first thing the browser does is render the block-level element to determine what 
the physical dimensions of the element are, given the font selected for the element, 
the contents of the element, and any other internal formatting instructions supplied 
by the style sheet. Then the browser looks at the element's padding, the border, and 
the margins to determine the space it actually requires on the page. Figure 16-1 
shows a representation of how these measures relate to one another. 



R F:\HT ML*;cri2* htnl - Microsoft Internet Exploier 



25E 



J Fib Eul ]£kv! Cu ■dvuiiles Hdu 



4= , =* 

Bcok -orward 



e a a m 



S'Iod Refresh Home 



J ArlrrFss |[tf] l-\HIMI IV^h^Wml 



~3 



Cell Cell 2 


Cell". 


Ccl2 


Cell 3 Cell 4 


Cell 3 


Cell 4 









5j Lccal irtranet :cne 



Figure 16-1: A visual representation of 
how margins, borders, and padding relate 
to each other and the element they affect. 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



Chapter 16 ♦ Introducing Cascading Style Sheets 2V5 



Padding is the distance between the outside edges of the element and the border. 
The border \s a line or ridge. The margin is the distance between the border and the 
outer box of the next container. How you define the padding, border, and margin is 
described in detail in the following sections. 



Padding 



You don't need to define any padding, but if you are going to define a border, then 
you probably want to define padding so your element doesn't look too crowded. The 
default for an element is no padding. Figure 26-2 shows the same table with and 
without padding. You can see that the one without padding looks crowded. 



Hit Table Padding -Mozilla Firebird 



- da 



File Edit View Go Bookmarks Tools Help 



■ ■*; »^ j£ fj | Q http://localhost/Chapt er1G/tablepa[v] |C^~ 



Celll 


Cell 2 


Cell 3 


Cell 4 


Celll 


Cell 2 


Cell 3 


Cell 4 



Done 



Figure 16-2: Tables with (bottom) and without padding (top). 



Five properties are associated with padding. They are as follows: 



1. paddi 

2. paddi 

3. paddi 

4. paddi 



ng, which gives the same padding on all sides 

ng-top 
n g - r i g h t 
ng- bottom 



5. paddi ng-1 eft 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



276 Part III ♦ Controlling Presentation with CSS 



Get used to seeing the - top, - ri ght, - bottom, and - 1 eft additions to property 
names. This is how all box-related properties are specified. 

Suppose you want to define your paragraphs to have padding on the top, the left, 
and the right; you could use the following style sheet: 



padding-top: lOpx; 
padding-right: lOpx; 
paddi ng- 1 ef t : lOpx; 



T 'P Notice the liberal formatting of the style definitions in this section. As with other 

HTML coding, you will find it helpful to format your style definitions with liberal 
white space, namely line breaks and indents. 

Or, you could use shorthand to write out the padding properties, as follows: 



padding: lOpx lOpx Opx lOpx; 



You can always string the top, right, bottom, and left properties together in that 
order. The same shorthand works for margins and borders. Notice that no commas 
are used between the items in the list. 



Border 



The default is to have no border on elements. You can define a border in two 
different ways. Either you can define the width, color, and style of the border by side, 
or you can define the width, color, and style for the box individually. Two examples 
follow: 



blockquote 1 
bonden-width 
bonden -colon 
bonden -styl e 



lpt Ipt Opt lpt; 

black; 

solid; 



The previous example creates a black, solid border for the top, right, and left sides of 
the list. 

blockquote 1 

bonden-top: lpt solid black; 
bonden-night: lpt solid black; 
bonden-left: lpt solid black; 



Both these examples create the same border. The border is inserted between the 
padding, if there is any, and the margin, if there is any. Valid values for border style 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



Chapter 16 ♦ Introducing Cascading Style Sheets 277 



are as follows: 

♦ none 

♦ dotted 

♦ dashed 

♦ solid 

♦ double 

♦ groove 

♦ ridge 

♦ inset 

♦ outset 

Or, if you want to create a border that is the same on all four sides, you can use the 
border property: 

blockquote { 

border: lpt solid black; 



Margins 



Margins create white space outside of the border. Notice in Figure 26-2 that the two 
tables are immediately adjacent to each other. This is because neither one has 
margins. Margins are created with the ma rgi n, margi n-top, margi n- ri ght, 
margin-bottom, and margin-left properties. They work exactly the same as the 
padding property described in the previous section. 



CSS Levels 1,2, and 3 



There are three levels of CSS — two actual specifications and a third level in 
recommendation status. Notable differences exist between the two standards and the 
third recommendation. The main differences between the three levels are as follows: 



4- CSS1 defines basic style functionality, with limited font and limited positioning 
support. 

4- CSS2 adds aural properties, paged media, better font and positioning support. 
Many other properties have been refined as well. 

♦ CSS3 adds presentation-style properties, allowing you to effectively build 
presentations (think Microsoft PowerPoint) from Web documents. 

Keep in mind that you don't have to specify the level of CSS you are using for your 
documents, but you do have to be conscientious about what user agents will be 
accessing your site. Although most browsers support CSS, the level of support varies 



P1:FRU 
WY022-16 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 14, 2004 19:27 



278 Part III ♦ Controlling Presentation with CSS 



dramatically. It's always best to test your implementation on target user agents 
before widely deploying your documents. 



Summary 



This chapter introduced you to the subject of CSS. You learned what CSS is and the 
various methods to implement it with your documents. Lastly, you learned the major 
differences between the various CSS levels. The next few chapters break down the 
CSS properties into various sections and cover them individually. 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Creating Style 
Rules 



The first step to understanding Cascading Style Sheets 
(CSS) is to understand how to correctly write style rules. 
There are two pieces to each rule: the selector, which tells the 
rule what elements it should apply to, and the rule itself, 
which does all the formatting. This chapter delves into the 
many levels and types of selectors and the different metrics 
you can use when setting style properties. 



Note 



Half the battle with styles is remembering the syn- 
tax, selector methods, and all the property names. If 
you find yourself constantly working with CSS and writ- 
ing definitions, you might want to invest in an editor 
that can do most of the work for you. An example 
of a program that gets the job done without unnec- 
essary features is Macromedia Homesite (http : / /www 
. macromedi a . com). Homesite is a basic editor that can 
take the tedium out of mundane tasks like style writing. 
Other, more full-featured programs also have helpful CSS 
tools. See Chapter 34 for examples of Web publishing 
software. 



C H A P T E 



♦ ♦ ♦ ♦ 
In This Chapter 

Understanding Selectors 
Understanding Inheritance 
Pseudo-Classes 
Pseudo-Elements 
Shorthand Expressions 
Property Value Metrics 

♦ ♦ ♦ ♦ 



Understanding Selectors 



CSS styles work by taking a definition of attributes and 
applying them to any tags that match the selector associated 
with the definition. 

As a review, CSS style definitions follow this format: 



selector { propertyl: 
propertyN: valueN; I 



valuel; propertyZ: value2; 



The selector is what browsers use to match tags in a 
document to apply the definition. The selector can take 
several different forms, offering a lot of flexibility to match 
almost any use of tags in a document. 



279 



PI: JYS 

WY022-17 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



280 Part III ♦ Controlling Presentation with CSS 



Matching elements by name 

The easiest selector to understand is the plain element selector, as in the following 
example: 

hi 1 color: red ; ) 

Using the actual element name (h 1) as the selector causes all those tags to be 
formatted with the attributes of the definition (color: red). You can also attach 
multiple selectors to the same definition by listing them all in the selector area, 
separated by commas. For example, this definition will affect all heading tags in the 
document: 

hi, h2, h3, 4h, h5, h6 1 color: red; I 



Using the universal selector 



The universal selector can be used to match any element in the document. The 
universal selector is an asterisk (*). As an extreme example, you can use the 
universal selector to match every tag in a document: 

* { col or : red ; 1 

Every tag will have the color: red attribute applied to it. Of course, you would 
rarely want a definition to apply to all elements of a document. You can also use the 
universal selector to match other elements of the selector. For example, using the 
child/descendent matching method of selectors, you can use the universal selector 
to select everything between the parent and the descendent. The following selector 
matches any <ol > tag that is a descendent of a <td> tag, which is a descendent of a 
<tr> tag: 

tr td ol 1 col or : red ; 1 

Note You'll find more information on child/descendent selectors in the Matching 

child, descendent, and adjacent sibling elements section later in this chapter. 

However, this selector rule is very strict, requiring all three elements. If you also 
wanted to include descendent <ol > elements of <td> elements, you would need to 
specify a separate selector, or use the universal selector to match all elements 
between <t r> and <ol >, as in the following example: 

tr * ol 1 color: red ; I 

You can use this technique with any of the selector forms discussed in this chapter. 



Matching elements by class 



You can also use selectors to match elements by class. Why would you want to do 
this? Suppose that you had two areas on your page with different backgrounds, one 
light and one dark. You would want the light background area to have dark text and 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 281 



the dark background area to have light text. You could then use the class attribute in 
select elements within those areas to ensure that the appropriate styles were 
applied. 

To specify a class to match with a selector you append a period and the class name 
to the selector. For example, this style will match any paragraph tag with a class of 

darkarea: 

p.darkarea { color: white; ) 

For example, suppose that this paragraph was in the area of the document with the 
dark background: 

<p cl ass="dar karea">Lorem ipsum dolor sit amet, consectetuer 
adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad 
minim veniam, quis nostrud exerci tat ion ullamcorper suscipit 
lobortis nisi ut aliquip ex ea commodo consequat . </p> 

The specification of the darkarea class with the paragraph tag will cause the 
paragraph's text to be rendered in white. 

T 'P The universal selector can be used to indicate that all tags with a given class 

^ should have the style applied. For example, this style definition will apply to all 
v tags with the da rkarea class: 

*.dankanea { color: white; } 

However, you can also omit the universal selector, specifying only the class for 
the same effect: 

.darkarea { color: white; } 

Matching elements by identifier 

Just as you can match classes, you can also match element identifiers (the i d 
attribute). To match identifiers, you use the pound sign (#) in the selector. For 
example, the following style will match any tag that has an i d attribute of comment: 

^comment { background -col or : green; ) 

Matching elements that contain 
a specified attribute 

Besides class and id, you can match any attribute. To do so, specify the attribute and 
the value(s) you want to match in the selector. This form of the selector has the 
following format: 



el ement[attribute=" value"] 



PI: JYS 

WY022-17 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



282 Part III ♦ Controlling Presentation with CSS 



For example, if you want to match any table with a border attribute set to 3, you 
could use this definition: 

tabl e[border="3"] 

You can also match elements that contain the attribute, no matter what the value of 
the attribute is set to. For example, to match any table with a border attribute, you 
could use this definition: 

tabl e[border] 

T 'P You can combine the various selector formats for even more specificity. For 

example, the following selector will match table tags with a class attribute of 

datal i st, and a border attribute of 3: 

table.datalist[border="3"] 

You can stack multiple attribute definitions for more specificity. Each attribute is 
specified in its own bracketed expression. For example, if you wanted to match 
tables with a border attribute of 3 and a wi dth attribute of 100%, you could use 
this selector: 

table[border="3"][width="100r'] 

Note Two other attribute-matching methods can be used to match a value in a space 

or hyphen-separated list in an attribute's value. To match a value in a space- 
separated list, you use ~= instead of the usual equal sign (=). To match a value 
in a hyphen-separated list, you use |= instead of the usual equal sign (=). For 
example, the following definition would match "us" in a space-separated value 
in the language attribute: 

[language~="us"] 



Matching child, descendent, and adjacent 
sibling elements 

One of the most powerful selector methods you can use for matching elements is 
defining selectors that use the relationships between elements. For example, you can 
specify a style for italic text only when in a heading, or list items in ordered lists. 



Understanding document hierarchy 

All elements in a document are related to other elements. The hierarchy follows the 
same nomenclature as family trees — ancestors, parents, children, descendents, and 
siblings. For example, consider the following code and Figure 17-1, which shows a 
typical HTML document and its hierarchy. 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 283 



html) 

body) 

di v c 

<hl> 

<tab 

<t 

<t 

</ta 

<p>L 

el it 

dol o 

veni 

1 obo 

/ d i v > 

di v c 

<hl 

<p>L 

el it 

dol o 

veni 

1 obo 

<ol 

<1 

<1 

<1 

</ol 

/ d i v > 

/body 

/html 



1 ass= 
H e a d i 
le> 
rXtd 
rXtd 
ble> 
orem 
, sed 
re ma 
am , q 
rti s 

1 ass= 
H e a d i 
orem 
, sed 
re ma 
am , q 
rti s 
An or 
i > F i r 
i > S e c 
i>Thi 



d i v 1 " > 
ng K/hl> 

>Cell K/td) 
>Cell 3</td) 



;td>Cell 2</td> 
:td>Cell 4</td) 



7tr> 
7tr> 



ipsum dolor sit amet, consectetuer adipiscing 

diam nonummy nibh euismod tincidunt ut laoreet 
gna aliquam erat volutpat. Ut wisi enim ad minim 
uis nostrud exerci tation ullamcorper suscipit 
nisi ut aliquip ex ea commodo consequat . </p> 

"div2"> 

ng 2</hl> 

ipsum dolor sit amet, consectetuer adipiscing 

diam nonummy nibh euismod tincidunt ut laoreet 
gna aliquam erat volutpat. Ut wisi enim ad minim 
uis nostrud exerci tation ullamcorper suscipit 
nisi ut aliquip ex ea commodo consequat . </p> 
d e r e d list 
st element 
ond element 
rd element 



divl 



hi 



table 



body 



td 



td 



div2 



hi 











I 




td 




td 












tr 















I 






ol 












- li 








- li 








- li 



Figure 17-1: A graphical representation of the document's 
hierarchy. 



PI: JYS 

WY022-17 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



284 Part III ♦ Controlling Presentation with CSS 



Ancestors and descendents 

Ancestors and descendents are elements that are linked by lineage, no matter the 
distance. For example, in Figure 17-1 the list elements under d i v2 are descendents of 
the body element, and the body element is their ancestor. 

Parents and children 

Parents and children are elements that are directly connected in lineage. For 
example, in Figure 17-1 the table rows under di vl are children of the table element, 
which is their parent. 

Siblings 

Siblings are children that share the same, direct parent. In Figure 17-1, the list 
elements under d i v 2 are siblings of each other. The header, paragraph, and table 
elements are also siblings because they share the same, direct parent (d i v 1). 

Selector mechanisms for hierarchies 

There are several selector mechanisms to use in defining rules, specifying matched 
elements by their relationships to other elements. 

To specify ancestor and descendent relationships, you list all involved elements 
separated by spaces. For example, the following selector matches the list elements 
in Figure 17-1: 

d i v . d i v 2 1 i 

To specify parent and child relationships, you list all involved elements separated by 
a right angle bracket (>). For example, the following selector matches the table 
element in Figure 17-1: 

div.divl table 

To specify sibling relationships, you list all involved elements separated by plus 
signs (+). For example, the following selector matches the paragraph element 
under di vl in Figure 17-1: 

table + p 



Understanding Inheritance 



Inheritance is the act of picking up attributes from one's ancestors. In CSS, all 
foreground properties are passed down (inherited) to descendent elements. For 
example, this definition would result in all elements being rendered in blue, because 
every tag in the document is a descendent of the body tag: 

body { col or : blue; 1 

Note that this is only true for foreground properties. Background properties 
(background color, image, and so on) are not inherited. 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 285 



Inheritance is the default action unless an element has the same attribute defined 
differently. For example, the following definitions result in all elements, except tor 
paragraphs with a notbl ue class, being rendered in blue: 

body 1 color: blue; ) 

p . notbl ue { color: red ; 1 

Instead of bl ue, the notbl ue paragraphs are rendered in red. 

Attributes that are not in conflict are cumulative on descendent elements. For 
example, the following rules result in paragraphs with an emphasi s class being 
rendered in bold, blue text: 

body 1 color: blue; ) 

p. emphasis { font-weight: bold; ) 



Pseudo-classes 



CSS has a handful of pseudo-classes that you can use to modify attributes of 
elements in your document. Pseudo-classes are identifiers that are understood by 
browsers to apply to a subset of elements, without the element needing to be 
explicitly tagged with the style. Such classes are typically dynamic and tracked by 
other means than the actual class attribute. 

For example, there are two pseudo-classes that can be used to modify the attributes 
of visited and unvisited links in the document (explained in the next section). If you 
use the pseudo-classes, you don't have to actually specify the classes in individual 
links — the browser determines which links fit into which class (visited or not) and 
applies the style(s) appropriately. 

The following sections discuss the various pseudo-classes available in CSS. 



Defining link styles 



A handful of pseudo-classes can be used with links (usually <a > tags). The link 
pseudo-classes are listed in Table 17-1. 





Table 17-1 
Link Pseudo-classes 


Pseudo-class 


Matches 


:link 


Unvisited links 


:visited 


Visited links 


:active 


Active links 


:hover 


The link that the browser pointer is hovering over 


:focus 


The link that currently has the user interface focus 



PI: JYS 

WY022-17 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



286 Part III ♦ Controlling Presentation with CSS 



For example, the following definition will cause all unvisited links in the document to 
be rendered in blue, visited links in red, and when hovered over, green: 

: 1 i n k 1 color: blue; I 
:visited 1 color: red; 1 
: hover {color: green ; ) 

Note the order of the definitions; it is important. Because the link participation in 
the classes is dynamic, : hover must be the last definition. If the order of : vi si ted 
and : hover were reversed, visited links would not turn green when hovered over 
because the : vi s i ted color attribute would override the : hove r color attribute. 
The same ordering is important when using the : focus pseudo-class — place it last 
in the list of definitions affecting similar elements. 

You can combine pseudo-classes with other selector methods, as needed. For 
example, if you wanted all links with a class attribute of i mportant to be rendered 
in a bold font, you could use the following code: 

:1 ink. important { font- weight: bold; I 

<a href="http://something. example. com/ important. html" 
cl ass="important">An important message</a> 



The :first-child pseudo-class 



The :first-child pseudo-class applies the designated style(s) to the fi rst child 
element of a specified element. You can use this class to add additional space or 
otherwise change the formatting of the fi rst child element. For example, to indent 
the first paragraph of all <di v> elements, you could use this definition: 

div > p:first-child 1 text- indent: 25px; I 



The :lang pseudo-class 



The language pseudo-class (: 1 a ng) allows constructing selectors based on the 
language setting for specific tags. This is useful in documents that must appeal to 
multiple languages that have different conventions for certain language constructs. 
For example, the French language typically uses angle brackets (< and >) for quoting 
purposes, while the English language uses quote marks (' and '). 

In a document that needs to address this difference, you can use the : 1 a ng 
pseudo-class to change the quote marks appropriately. The following code changes 
the <bl ockquote> tag appropriately for the language being used: 

/* Two levels of quotes for two languages */ 

:lang(en) { quotes: ; I 

:lang(fr) 1 quotes: "<<" ">>" "<" ">"; 1 

/* Add quotes (before and after) to blockquote */ 
bl ockquote : before { content: open-quote; 1 
bl ockquote : after 1 content: close-quote; 1 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 287 



Note 



The pseudo-elements : before and : after are covered later in this chapter 
in the Pseudo-elements section. 



The : 1 a ng selectors will apply to all elements in the document. However, not all 
elements make use of the quotes property, so the effect will be transparent for most 
elements. The second two definitions in the preceding example add quotes to the 
bl ockquote element, which typically does not include quotes. 



Pseudo-elements 



Pseudo-elements are another virtual construct to help you apply styles dynamically 
to elements in your documents. For example, the :fl rst- 1 i ne pseudo-element 
applies a style to the first line of an element dynamically — that is, as the first line 
grows or shrinks the browser adjusts the style coverage accordingly. 

The various pseudo-elements are covered in the following sections. 



Applying styles to the first line of an element 

The :first-line pseudo-element allows you to specify a different definition for the 
first line of elements in the document. This is shown in the following code and 
Figure 17-2: 



DOCTYP 

"http: 

tml> 

ead> 

<title 

<styl e 
p :flr 
p . no 

</styl 

head) 

ody> 

DIN C 
class 

ited S 



E HTML PUBLIC "-//W3C//DTD HTML 4. 01// EK 
//www. w3.org/TR/html4/strict.dtd"> 



> F i r s t - 1 i n e formatting</title> 

type="text/css"> 
st -line 1 text -decorati on : underline; 1 
1 i n e : fi r s t - 1 i n e { text-decoration: none; 
e> 



ONGRESS, July 4, 1776. </hl> 

="nol i ne">The unanimous Declaration of the thirteen 
tates of Ameri ca , </p> 



<p>When in the Course of human events, it becomes necessary 
for one people to dissolve the political bands which have 
connected them with another, and to assume among the powers 
of the earth, the separate and equal station to which 
the Laws of Nature and of Nature's God entitle them, a decent 
respect to the opinions of mankind requires that they should 
declare the causes which impel them to the sepa rat i on . </p> 

</body> 
</html> 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



288 Part III ♦ Controlling Presentation with CSS 



Jf) First-line formatting - Mozilla Firebird 



- -1 x 



File Edit View Go Bookmarks Tools Hel|> 



->-^4? , ffr | http://localhost/Chapter17/Fig17-2.htm [v] |Q. 'Chapter19/fig19-2.htrnl 



IN CONGRESS, July 4, 1776. 

The unanimous Declaration of the thirteen united States of America, 

When in the Course of human events, it becomes necessary for one people to dissolve the 
political bands which have connected them with another, and to assume among the powers of the 
earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle 
them, a decent respect to the opinions of mankind requires that they should declare the causes 
which impel them to the separation. 



Done 



Figure 17-2: :flrst-l i ne pseudo-element can be used to affect only the 
first line of elements. 



Note 



Use of the : first! ine pseudo-element is somewhat hindered due to the 
limited range of properties it can affect. Only properties in the following groups 
can be applied using : first-line: font properties, color properties, back- 
ground properties, word-spacing, letter-spacing, text -decoration, 
verti cal -al i gn, text-transform, line-height, text-shadow, and 
cl ear. 



Note that the preceding code example uses classes to manage elements by 
exception. Since we want most paragraphs to have their first line underlined, a 
universal selector is defined to apply to all paragraph tags. A second selector, using a 
class (nol i ne), is defined to apply to elements that have their class set to nol i ne. 
This helps simplify our document — we only have to add class attributes to the 
exceptions instead of the rule. 



Applying styles to the first letter of an element 

Just as the : fi r s t - 1 i n e pseudo-element can be used to affect the properties of the 
first line of an element, the : fi r s t - 1 etter pseudo-element can be used to affect the 
first letter of an element. You can use this to achieve typographic effects such as 
dropcaps, as shown in the following code and Figure 17-3: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 289 



</h 
<bo 
<hl 

<P> 
thi 



(tit 
Csty 

P- 

fo 

bo 

ma 

C/st 

ead 

dy> 

>IN 

The 

rte 

cl a 

bee 

ds 

"9 
whi 

ece 

y s 

ara 
ody 
tml 



le>Drop cap f ormatt i ng</t i tl e> 

le type="text/css"> 

dropcap :first -1 etter { font-size: 3em; 

nt-weight: bold; float: left; 

rder: solid Ipx black; padding: . lem; 

rgin: .2em .2em 0; I 

yle> 



CONGRESS, July 4, 1776. </hl> 

unanimous Declaration of the 
en united States of America, </p> 
ss="dropcap">When in the Course of human events, 
omes necessary for one people to dissolve the political 
which have connected them with another, and to assume 
the powers of the earth, the separate and equal station 
ch the Laws of Nature and of Nature's God entitle them, 
nt respect to the opinions of mankind requires that 
hould declare the causes which impel them to the 
t i o n . < / p > 



@ Drop cap formatting - Microsoft Internet Explorer 



- S)Q 



File Edit View Favoiites Tools Help 

P ix * ® 



If 



q - o a ia 



@'S 14 



Address @ http://loi:alhost/Chapterl7/Figl7-3.ritml 



BB< 






IN CONGRESS, July 4, 1776. 

The unanimous Declaration of the thirteen united States of America, 



When in the Course of human events, it becomes necessary for one people to dissolve 
the political bands which have connected them with another, and to assume among 

the powers of the earth, the separate and equal station to which the Laws of Nature and of 
Nature's God entitle them, a decent respect to the opinions of mankind requires that they should 
declare the causes which impel them to the separation. 



\J Local intranet 



Figure 17-3: The :firstl etter pseudo-element can be used to achieve effects 
such as drop caps. 

Specifying before and after text 

You can use the : bef o re and : a f te r pseudo-elements to autogenerate content 
before and after specific elements. These pseudo-elements were used in the section, 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



290 Part III ♦ Controlling Presentation with CSS 



The : 1 a ng pseudo-class, to add quote marks to the beginning and ending of 

<bl ockquote> elements: 

bl ockquote : before { content: '"'; ) 
bl ockquote : after 1 content: '"'; I 

Note the use of the content property. This property can assign specific content to 
content-generating selectors. In this case, quote marks are assigned to the before 
and after properties so that <bl ockquote) elements will begin and end with 
quotes, as shown in Figure 17-4. 



uto-qiiote marks - Mozilla Fiieltiiil 



File Edit View Go Bookmarks Tools Hel|> 



<-i 



- 4 - *$ , fj} | http://localhost/Chapter17/Fig17-4.[y] |Q. 'Chapter19/fig19-2.html 



IN CONGRESS, July 4, 1776. 

The unanimous Declaration of the thirteen united States of America, 

"When in the Course of human events, it becomes necessary for one people to 
dissolve the political bands which have connected them with another, and to 
assume among the powers of the earth, the separate and equal station to which 
the Laws of Nature and of Nature's God entitle them, a decent respect to the 
opinions of mankind requires that they should declare the causes which impel 
them to the separation." 



Done 



Note 



Figure 17-4: Opera supports generated content, as demonstrated by the 
generated quotes around the <bl ockquote) paragraph. 

Many browsers do not support CSS-generated content. See Appendix B for 
more information on what properties are supported by which browsers. 



Generated content breaks the division of content and presentation, of which CSS is 
supposed to stick to presentation. However, additional content is sometimes 
necessary to enhance the presentation. Besides adding elements such as quote 
marks, you can also create counters for custom numbered lists and other more 
powerful features. 




More information on CSS content generation can be found in Chapter 19. 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 291 



Shorthand Expressions 



CSS supports many properties for fine control over elements. For example, the 
following properties all apply to borders: 

4- border 

♦ border-collapse 

♦ border-spacing 

♦ border-top 

♦ border-right 

♦ border-bottom 

♦ border-left 

♦ border-color 

♦ border-top-color 

♦ border-right-color 

♦ border-bottom-color 

♦ border-left-color 

♦ border-style 

♦ border-top-style 
4 border-right-style 

4- border-bottom-style 

4- border-left-style 

4 border-width 

4 border-top-width 

4 border-right-width 

4 border-bottom-width 

4 border-left-width 

Several of these properties are shorthand properties, which enable you to set 
multiple properties at a time. For example, to set an element's border as shown in 
Figure 17-5, you could use the following definition: 

p. bordered { 

border-top-width: lpx; 

border -top-styl e : solid; 

border -top-col or : black; 

border-right-width: 2px; 
border - ri ght -styl e : dashed; 
border-right-color: red; 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



292 Part III ♦ Controlling Presentation with CSS 



border -bottom-width 

border -bottom-style 
border -bottom-col or 



Ipx ; 

solid; 

black; 



border-left-width 
border -1 eft -sty! e 
border -1 eft -col or 



2px ; 
dashec 
red ; 



DU Border formatting - Mozilla Firebird 



QOS 



File Edit View Go Bookmarks Tools Hel|> 



^ 



" 4- ' *t& ^ http://localhost/Chaptet[v] |Q, f C hapter19/fig1 9-2. html 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonumtny 
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi 
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit obortis nisi 
ut aliquip ex ea commodo consequat. 



Done 



Figure 17-5: A paragraph using different borders requires multiple 
properties to be set. 



However, you can use the border- side properties to shorten the definition, 
defining the border width, style, and color with one property: 

p. bordered 1 

border-top: Ipx solid black; 
border-right: 2px dashed red; 
border -bottom : Ipx solid black; 
border-left: 2px dashed red; 



You could further simplify this style by using the border property, which allows you 
to set all the sides to the same property and then list the exceptions: 



p. bordered 1 

border: Ipx solid black; 



PI: JYS 

WY022-17 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 293 



border-right: 2 p x dashed red; 
border-left: 2px dashed red; 



The preceding definition first sets all the sides to the same width, style, and color. 
Then the left and right are set to their proper properties, overriding the border 
property's left and right side settings. 

Cross- See Appendix B for more information on the various shortcuts in CSS. 

Reference 




T 'P Avoid overusing shortcut properties or being too ingenious in setting styles with 

\ minimal properties. Although you may save in typing, you will also decrease the 

' legibility of your code. Take a look at the example definitions in this section— 

although the first example is lengthy, it leaves little to the imagination of how 

the border is being formatted. 



Property Value Metrics 



Now that you know how to apply values to properties, let's talk about the values 
themselves. You can specify your values using several different metrics, depending 
upon your needs and use. 

CSS styles support the following metrics: 

4- CSS keywords and other properties, such as thin, thick, transparent, ridge, and 
so forth 

♦ Real-world measures 

• inches (in) 

• centimeters (cm) 

• millimeters (mm) 

• points (pt) — the points used by CSS2 are equal to l/72 th of an inch 

• picas (pc) — 1 pica is equal to 12 points 

♦ Screen measures in pixels (px) 

4- Relational to font size (font size (em) or x-height size (ex) 
4- Percentages (%) 

♦ Color codes (# r r g g b b or r g b ( r , g , b )) 

♦ Angles 

• degrees (deg) 

• grads (grad) 

• radians (rad) 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



294 Part III ♦ Controlling Presentation with CSS 

♦ Time values (seconds (s) and milliseconds (ms)) — used with aural style sheets 

♦ Frequencies (Hertz (Hz) and kilo Hertz (kHz)) — used with aural style sheets 

♦ Textual strings 



Which units you use depends on which properties you are setting and what the 
application of the document is. For example, it doesn't make any sense to set the 
document's property values to inches or centimeters unless the user agent's display 
is calibrated in real-world measures or your document is meant to be printed. 




Cross- 
Reference 



See Chapter 24 for more information about formatting documents for printing. 
See the relevant chapters in Part III for examples of how to use the various 
metric values in properties. See Appendix B for a list of what properties support 
which metrics. 



In the case of relational values (percentages, em, and so on), the actual value is 
calculated on the element's parent settings. For example, consider the following two 
definitions for the < i > element. Both of definitions will set the font size of all italic 
elements to llpts, by specifying 1.1 times the parent's font size, or 110% of the 
parent's font size. The output of this code is shown in Figure 17-6. 



Note 



DOCTYP 
"http: 
tml> 
ead> 
<title 
<style 
/* S 

P f 
/* S 
i . de 
/* S 
i . de 
</styl 
head) 
ody> 
<p>Lor 
a d i p i s 
t i n c i d 
erat v 
nost ru 
a 1 i q u i 
body) 
html) 



E HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 
//www. w3.org/TR/html4/strict.dtd"> 



>Border formatting</title> 

type="text/css"> 
et paragraph font to lOpt */ 
font-size: lOpt; ) 
et font to 1.1 * parent */ 
fl { font-size: l.lem; I 
et font to 110% parent */ 
f2 { font-size: 110%; } 
e> 



em ipsum dolor sit amet, <i cl ass="def l">consectetuer 

c i n g < / i > elit, sed diam nonummy nibh euismod 

unt Lit laoreet dolore magna <i cl ass="def 2">al i quam 

olutpat</i>. Ut wisi enim ad minim veniam, quis 

d exerci tat ion ullamcorper suscipit obortis nisi ut 

p ex ea commodo consequat . </p> 



The em unit can be quite powerful because it allows you to specify a value 
that changes as the element sizes change around it. However, using the em 
unit can have unpredictable results. As such, em is best used when you need 
a relational, not absolute, value. 



PI: JYS 
WY022-17 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



Chapter 17 ♦ Creating Style Rules 295 



ffl Formatting with em - Moiilla Firebird 



bob 



File Edit View Go Bookmarks Tools Help 



- ■§>' » ^£ £ fjj | hllp://localhost/Chaptet|-v| |Q, f Chapter19/fig19-2.htmT 



Lorem ipsum dolor sit amet, conssctetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat voluipat. Ut wisi enim ad minim 
veniam, quis nostrud exercitationullamcorper suscipit obortis nisi ut aliquip ex ea commodo 
consequat. 



Done 



Figure 17-6: Using the em and percentage metrics, you can define 
elements to be a relative size, driven by the elements around them. 



Summary 



This chapter rounded out the basics of CSS. You learned how to construct valid CSS 
rules using simple and complex selectors, the role inheritance plays throughout 
document styles, and the different metrics you can use to specify properties. 



PI: JYS 

WY022-17 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:18 



296 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Fonts 



I remember working with an award-winning print designer 
in Chicago who was so resistant to computers and desktop 
graphic software that he eventually disappeared from the 
industry. Good print designers have strong feelings about 
typography as an art form, and many of them resisted early 
desktop publishing tools, not so much because these tools 
couldn't perform, but because they ended up in the hands of a 
new generation of designers who, in the mind of the old 
school, didn't truly appreciate typography. 

When print designers began to encounter Web design projects, 
they were aghast. Most designers don't like to compromise 
when it comes to the quality of their designs, and the Web is 
all about compromise. Discovering that the font they so 
carefully chose would likely not appear as they hoped but, 
worse, would more than likely be replaced with another font, 
was a traumatic experience for many traditionalists. 

Today, the Web is still all about compromise. Flash hasn't 
changed that. Scalable Vector Graphics (SVG) haven't changed 
it (though they both could yet), and today's browsers certainly 
haven't changed it. However, there is considerably more you 
can do with fonts than you were able to do at one time, and 
some careful planning and a little extra work can give you 
considerable control over the way your Web pages render 
fonts. This chapter explores fonts, why you need to 
understand them, and how you can have your pages render at 
least close to something like you had in mind when you 
originally conceived your design. 



♦ ♦ ♦ ♦ 
In This Chapter 

Web Typography Basics 

Working with Font Styling 
Attributes 

Downloading Fonts 
Automatically 



Web Typography Basics 



Fonts basically consist of glyphs, which are the actual 
machine-based descriptions of individual members of a font 
family. These descriptions are based on either a vector-based 
outline or a pixel-based bitmap. Each font exists on an 
invisible grid called an em square, which forms the boundaries 
that a font description relies on. See Figure 18-1 for a 
description of a glyph's properties. 




297 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



298 Part III ♦ Controlling Presentation with CSS 



Height of Lowercase Glyph 



Height of Uppercase Glyph 



-^.j a jglypffi 



f 



J descent 



- baseline 



. , (Maximum unaccented depth) 

em square grid: v r ' 

TrueType, OpenType: 2048 divisions 

Type 1 PostScript: 1000 divisions 

Figure 18-1: Glyph attributes. 

As you can see in Figure 18-1, the em square determines the height boundaries that a 
font can meet on the grid. Print-based typefaces, such as PostScript, determine exact 
widths and heights by breaking the em square up into smaller pieces (1,000 pieces 
for PostScript, 2,048 for TrueType). OpenType, which is found on both Web-based 
fonts (see the section towards the end of this chapter on downloadable Web fonts), 
also breaks an em square up into 2,400 parcels. Machines then use these parcels as 
ways to exactly measure distance within an em square and the existence of different 
parts of a font glyph. For example, say the bottom of a g is measured within the 
scope of those divisions. The positioning based on those divisions is what gives each 
font its unique characteristics. 

The wrong way to describe fonts 

It may seem a little heavy-handed to say that just because the W3C has deprecated 
an element (meaning that the element is discontinued and is no longer part of any 
formal specification) you shouldn't use it. But when you realize that its use leads to 
extremely tedious maintenance issues, the argument suddenly seems a bit less 
heavy-handed. These maintenance issues arise because of the very nature of how a 
font element works. 

You can use the font element to render font attributes. The font element has been 
deprecated, and you won't even find it in the XHTML 1.1 specification. The theory 
behind its use was that it would control the way a font looked. In practice, ghastly 
things happened. For example, users might set a font size to 1 that on some screens 
is so tiny as to be unreadable, or a font size at 3, which on a screen whose user has 
poor vision takes up the entire screen for a couple of words because the user's 
browser preferences are set with large font sizes. Still, you might work for a large site 
that continues to insist on using this dinosaur, so here are this element's attributes: 

♦ S I Z E=C DATA (font size adjustment) 

♦ C0L0R=Color (font color adjustment) 

♦ FAC E=C DATA (font face adjustment) 

♦ HTML 4.0 core attributes 

♦ HTML 4.0 internationalization attributes 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Chapter 18 ♦ Fonts 299 



You can see these attributes at work in the following example: 

<font size="l" f ace="Hel veti ca , Arial, Verdana, sans-serif" 
color="blue" lang="en-US" cl ass=" . smal 1 " styl e="f ont-f ami ly : 

Times, serif;" i d="conf usi n g El ement">Thi s is an HTML 
deprecated el ement I </f ont> 

Load the code from Listing 18-1 into your browser and you'll see something similar 
to that shown in Figure 18-2. 



Listing 18-1 : Using the Font Element to Name a Font Family 

<body> 

<font size="l" f ace="Hel veti ca , Arial, Verdana, sans- 
serif" color="blue" lang="en-US" cl ass=" . smal 1 " style="font- 
family: Times, serif;" i d="Conf usi ngEl ement">Thi s is an HTML 
deprecated <span style="font- 
size:28px;">el ement !</span></font> 
</body> 



3 C:\Documents and Settings\ChucklBooks\WiLey\Ch18lL1801 .htm - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



I Address Lg C:\Docunientc and EetthgciChjck1Boo^\vViley\ChlE\L13ul.htn 



This is an HTML deprecated eleilieilt! 



3B l 









> m/ compute' 



Figure 18-2: The attempt to style a string of characters using the font element fails. 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



300 Part III ♦ Controlling Presentation with CSS 



You'll notice several things about Listing 18-1 and Figure 18-2. First, no matter what 
fonts you have installed on your system, if you're testing in a modern browser, you 
won't see sans-serif fonts rendered even though you call for them in the font 
element. This is because you're using a stylesheet, which overrules font element 
attribute information in CSS-compliant browsers. To make the font element's 
attributes work, you must be certain that no style sheet rules are in conflict with 
your intentions. So delete the style sheet information and the class attribute so 
that the font element looks like this: 

<font size="l" f ace="Hel veti ca , Arial, Verdana, sans-serif" 
color="blue" i d="LessConf usi ngEl ement">Thi s is an HTML 
deprecated <span style="font- 
size:28px;">element!</span></font> 

Your browser window will now display, as shown in Figure 18-3. 





j Hie Edit View Favorites Tcols Help 


if 


| B'O a a « >= *c • a-a i-3 o ■* 




: Address \J^) C:\Cocu"nen:s and S2ttings\Chuck\Eook5\Wiley\Chl^Firgurel8-2.htn 


v|Sg 



This is an HTML clep-ecatecl element! 






S) 3one i g My Computer 

Figure 18-3: A string of characters successfully styled by using the font element. 



If you name a font family with spaces between characters, you need to enclose the 
name in single quotes, as shown in bold in the following: 



<font size="l" face=" 'Helvetica Narrow', Arial, Verdana, 
sans -seri f " > T h i s is an HTML deprecated <span styl e="f ont- 
size:28px;">element!</span></font> 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 



14:58 



Chapter 18 ♦ Fonts 301 



The right way to describe fonts 

If you examine Figure 18-4 and Listing 18-2, which creates the screen rendered in that 
figure, you'll immediately see the benefits of working with the right way of managing 
fonts, which is CSS. 



j Hie Edit View Favorites Tcols Help 




1 


, *r «• ■ - • ,-v B - 


^9* 




j Address |g] C:\CocuTien:s and S3ttings\Chuck\Boots\Wiley\ChlSiL1802.htm 




v BJgo 



: Links ^&j CNN :: craigslist ^ - Cubs ^ . Dictionary - dotNet Tutorial 



Free Hot-nail ^Google ^) 115 HELP ^] Javertising 



Font Size 


Font Size* 


Font Size - 


CSS 


7cart Sim = 1 


Font Size = +1 


honti^ize = -1 


font-size: Y2px 


Font Size =2 


Tout Size = 1 2 


Fan Siffi = -2 


font- size: ljpx 


Font Sazp. = '■I 


Font Size - +3 


Fail Siffi = -3 


font- size: Hpi 


Foul Size - 4 


Font Size 

= +4 


Fort Sk* = 4 


font-size: 15ps 


Font Size = 5 


Font Size 

= +5 


Fort Six - -5 


font-size: I6"px 


Lj f"V-#^T ^-iTtH 


£ n * ri ' 


Fan Slffi = -0 


font- size: l'/px 



A 



v 



3|) Done j My Computer 

Figure 18-4: A table of different font sizes shows a lack of consistency without CSS. 



Listing 18-2: Creating Font Sizes with CSS and the Font 
Element's Size Attribute 

<html> 

<head> 

<title>Font sizes</title> 

<meta http-equi v="Content -Type" content="text/html ; 

charset=i so -8859-1") 

<style type="text/css"> 




.12pixels {font-size: 12px 

. 1 3 p i x e 1 s (font-size: 13px 

.14pixels {font-size: 14px 

.15pixels (font-size: 15px 



Continued 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



302 Part III ♦ Controlling Presentation with CSS 



Listing 18-2: (continued) 

.16pixels {font-size: 1 6 p x ; I 
. 1 7 p i x e 1 s {font-size: 1 7 p x ; I 
.18pixels {font-size: 1 8 p x ; I 

.sans-senif {font-family: Frutigen, Arial, Helvetica, sans- 
serif; 1 

.sans-serif-b {font-family: Frutiger, Arial, Helvetica, sans- 
serif ; font -wei ght : 900;) 



<td wi 

b " > F o n t Si 

<td wi 

b " > F o n t Si 



</style> 
</head> 

<body> 

<table width="100^" border="0" eel 1 spaci ng="0" 
eel 1 paddi ng="5" styl e="border : #cccccc thin solid") 
<tr align="left" valign="top" bgcol or="#D5D5D5" > 

<td width="26^" val i gn="bottom" cl ass="sans -seri f -b">Font 
Size</td> 

dth="29%" val i gn="bottom" cl ass="sans -seri f - 
ze +</td> 

dth="17%" val i gn="bottom" cl ass="sans -seri f - 
ze -</td> 

<td width="28^" val i gn="bottom" cl ass="sans -seri f - 
b">CSS</td> 
</tr> 
<tr al ign="l eft" va 1 i gn="top"> 

<td><p><font size="l">Font Size = K/font> </p></td> 
<td><font size="+l">Font Size = +K/font> </td> 
<td><font size="-l">Font Size = -K/fontX/td> 
<td cl ass="12pi xel s">f ont -si ze : 12px</td> 
</tr> 

<!-- Additional rows of all the font-sizes here - download 
actual code to view all rows --> 
</table> 
<p>&nbsp ; </p> 
</body> 
</html> 



Notice the consistency of the sizes in the fourth column. If you open the file in your 
browser and change your browser's text size settings, you'll see that the fonts in the 
fourth column remain the same size, whereas the sizes in the first three columns, 
which don't use CSS for style formatting, all vary wildly. 



Hopefully, you're now convinced of the need to use CSS for styling your fonts. It's 
time to examine just how to do that. You can style several aspects of a font to make it 
bolder, italicized, add space between each character in a word, make it larger or 
smaller, make a font fatter or thinner, and add space between lines of text. For the 
syntactic details on how to use these styling capabilities, refer to Appendix B, CSS 
Levels 1 and 2 Quick Reference. 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Chapter 18 ♦ Fonts 303 



Working with Font Styling Attributes 

There are several styling attributes to control such characteristics as font families, 
sizes, holding, and spacing. 

Naming font families using CSS 

As I've shown, CSS provides a mechanism for rendering font families in a browser if 
those fonts are installed on a user's system. This is accomplished by creating either 
an inline style on an element such asatdorspan element, or by creating a class 
rule selector within the style element. Either way, the syntax is the same, with a list 
of font family names, each separated by a comma, contained within a set of braces: 

font-family ( A r i a 1 , Helvetica, sans-serif; 1 

The browser will look first for the Arial font in the preceding example, then the 
Helvetica font, then the "default" sans-serif font, which is whatever sans-serif font 
the user's operating system defaults to. 

If you name a font family with spaces between characters, you need to enclose the 
name in quotes, as shown in bold in the following: 

.myFontClass {font-family: 'Helvetica Narrow', sans-serif) 

In practice, it may be a good idea to use quotes even when there are no spaces 
between characters, because some versions of Netscape 4 have trouble recognizing 
font names otherwise. 

Listing 18-3 shows a brief example of creating both an inline style and calling a class 
selector to name a font family. 



Listing 18-3: Using Class Selector and Inline Style to 
Name a Font Family 

<html> 

<head> 

<title>Font sizes</title> 

<meta http-equi v="Content -Type" content="text/html ; 

charset=i so -8859-1") 

<style type="text/css"> 

<!-- 

.myFontClass {font-family: "Helvetica Narrow", sans-serif} 

--> 

</style> 

</head> 

<body> 

< p > T h i s is an <span styl e="f ont-f ami ly : 'Helvetica Narrow', 

sans-serif">inline</span> style.</p> 




Continued 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



304 Part III ♦ Controlling Presentation with CSS 



Listing 18-3: (continued) 



< p > T h i s uses a <span 

selector</span></p> 

</body> 

</html> 



cl ass="myFontCl ass">class 



The first bolded line shows a class selector named myFontCl ass, which is called by 
a s pa n element's class attribute (the last bolded code fragment). Figure 18-5 shows 
the results from rendering Listing 18-3 in the browser. 



ktmmamimmMMmmmm 



File Edit View Favorites Tools Help 



Q-O-HEt&JP^a'O 0- % m- d ® & 



I Address |g C:\Drjcuinents and Settirgs\Chuck\BooksiWiley\Chl8iLlEu3.htm 



_> 



This is an inline style. 
This uses a class selector 






VI 



^jDone 






J My Computer 



Figure 18-5: Rendering inline and class selector styles in the browser. 



Understanding font families 



When choosing font families for style sheets, it helps to understand some basic facts 
about fonts. For example, Arial and Helvetica are virtually identical. Arial is more 
commonly seen on Windows systems, and Helvetica on Macs and UNIX. It's best to 
call them both in a style sheet so that one of them will appear on a user's machine no 
matter what environment they're in. If you use the generic "sans-serif," you'll get the 
default sans-serif font on the user's system. So your best, lowest common 
denominator CSS font selector looks like this: 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Chapter 18 ♦ Fonts 305 



my FontCl ass (font-family: Arial, Helvetica, sans-serif 1 

Using this font will render a sans-serif font on the vast majority of modern browsers. 

To understand what a font family is, consider what a font family is not. Helvetica and 
Helvetica Narrow do not constitute a font family even though it's reasonable to 
suspect they would belong to the same family. Helvetica Narrow, by itself, is a font 
family. So is Helvetica, which actually refers to a basic kind of Helvetica font. 
Helvetica Condensed and other variations also exist. 

Understanding fonts and font availability 

The first thing to understand about font availability is that they probably aren't. In 
other words, all your best-laid plans when it comes to your design are likely to end 
up in complete disappointment. The reason? The fonts you name in a CSS file may, or 
may not, be on your users' computer systems. 

There are a few ways to ensure, for example, that Arial or Helvetica will appear as 
expected on your Web page for most of your audience. However, other than those 
two fonts, it's either a crapshoot or a lot of jumping through font hoops to get your 
fonts to render. The reason is simple. You can ask your user's browser to display the 
Frutiger font, for example, but if their system doesn't have it installed, the browser 
will simply display the next closest thing. How the browser decides that issue is an 
algorithmic process based on something called the Panose system (see sidebar), but 
the bottom line is that your HTML/CSS does not embed any actual font information 
or fonts; it merely requests that the browser display a font if that font happens to be 
on the user's system. 



How the Panose System Works 



Panose is a system of font substitution that uses a combination of mapping software (as in 
software that makes calculated comparisons), a ten-digit numbering system, and a classifi- 
cation method to help the browser match font property values. If that fails, the browser tries 
to find the closest match. For example, if you name Futura Extra Bold as the only font when 
you name a font family using either CSS or the font element's face attribute, and the user's 
system doesn't have Futura Extra Bold installed, the browser will probably use something 
like Arial Black because both fonts are heavy, wide sans-serif fonts. 



Working with font styles 



In traditional HTML, you can choose whether you want your font to appear in Roman 
style (non-italic) font or italics by using or not using the em or i elements: 



Emphasizing a 
el ement</i > . 



point with the <em>em element</em> or the <i>i 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



306 Part III ♦ Controlling Presentation with CSS 



The preceding code fragment results in the following in a browser: 

Emphasizing a point with the em element or the i element. 

If you want to really be sure even the earliest of browsers recognize your italics, em is 
the way to go. More importantly, it's a better choice because aural browsers should 
emphasize the contents of this element to sight-impaired users of your Web site. 

For this reason, this is one of the rare exceptions to the rule of using CSS for styling 
over HTML elements. However, there's nothing wrong with using both. To use italics 
in CSS, simply include the following either inline or in a rule selector: 

font-style: italic 

Note Be sure to call it "italic," not "italics" with an s. You can also use f ont-styl e : 

obi i que, but older versions of Netscape will not recognize it. 



Establishing font sizes 



Managing font size can be tricky even with CSS, but most developers seem to agree 
that the most reliable unit of measurement in CSS is the pixel. Managing font sizes in 
straight HTML, as noted earlier in the chapter, is about as inexact a science as there 
is, but the general rule is that it's supposed to work like that shown in Listing 18-2, 
provided earlier in this chapter, which shows all the available attribute values for the 
font element's size attribute. The way it's supposed to work, but often doesn't, is 
that using the plus sign (+) before a number (for example, +1 or +2) makes the font 
bigger relative to the default font size on the page. In production environments, this 
is not a reliable process. If you must use the font element's size attribute in your 
HTML (believe it or not, some large sites actually still make this a requirement), be 
aware that relative sizing using the plus sign before a number has inconsistent 
browser support, so your results will vary. 

To establish size using CSS, you simply name the property in your selector or inline 
style rule: 

.twelve (font-size: 12px| 
HI (font-size: xx-largel 
. x s m a 1 1 (font-size: 25%} 

In the preceding code fragment, three style rules are created, each with its own font 
size. The first creates a relative size using pixels as the unit of measure. Never spell 
out the word pixels in your style definition. Always use the form px. 

px is the most reliable unit of measure because it is based on the user's screen size, 
and the pixel resolution of his or her monitor. It also has virtually bug-free support 
across all browsers that support CSS. 

Other relative sizes include the following: 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Chapter 18 ♦ Fonts 307 



♦ em, for ems, is based on the em square of the base font size, so that 2em will 
render a font twice as large as your document's base font size. Support in 
Netscape 4 and IE3 is awful. 

♦ ex is based on the X height of the base font size, so that 2ex will render a font 
whose X character is twice as tall as the X character at the default, or base, 
font size. This is a meaningless unit in the real world, because support is either 
nonexistent or so poor as to make it worthless. 

The next line in the preceding code fragment sets an absolute size called xx - 1 a rge, 
although it isn't absolute among browsers, only the one browser your user is using 
to render the page, xx - 1 a rge is part of a larger collection that includes the 
following possible values: 

xx-small, x-small, small, medium, large, x-large, xx-large 
Other absolute sizes include the following: 

♦ pt for points. This is appropriate for pages that are used for printing, but is not 
a particularly reliable measure for managing screen-based fonts. 

♦ i n (inches), cm (centimeters), mm (millimeters), and pc (picas) are all rarely 
used on the Web, because they're designed with print production in mind. 

Finally, you can create a font size using a percentage by simply adding the % 
character next to the actual size. This will render the font x% of the base size. 

You can experiment with font sizes by modifying Listing 18-2. 

Using (or not using) font variants 

In theory, the CSS font-variant property lets you create fonts in uppercase that are 
smaller sizes in relative terms to their base size. In practice, it doesn't work very well 
in most browsers, and isn't worth your trouble. See the CSS reference in Appendix B 
for syntactical details. 

Bolding fonts by changing font weight 

Font weight refers to the stroke width of a font. If a font has a very thin, or light, 
stroke width, it will have a weight of 100. If it has a thick, or heavy, stroke width, it 
will be 900. Everything else is inbetween. To denote font width, you use a numeric 
set of values from 100 to 900 in increments of 100: 100, 200, 300, 400, and so on. Or, 
you can use the keywords bold, normal, bolder or lighter to set a value, which 
will be relative to the font weight of the element containing the font. 

The keyword bold is equal to the numeric value 700. An example of using 
font-weightin style rules written for a style element might be as follows: 

p { f ont -wei ght : normal! 
p. bold (font-weight: 9001 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



308 Part III ♦ Controlling Presentation with CSS 



Making font wider or thinner using font stretch 

This font property is supposed to allow you to make a font look fatter or thinner. 
Support is nonexistent, however. The curious among you can see the CSS reference 
in Appendix B for syntactical details. 



Line height and leading 



The CSS line-height property is another one of those nice-in-theory properties 
that just doesn't pan out in the real world. The syntax is supposed to let you set the 
space between lines in a process that in the print world is called leading. It works 
fairly well in Internet Explorer, but is a mess in Netscape 4. The syntax is easy enough: 



1 i n e - h e i g h t 
1 i n e - h e i g h t 
1 i n e - h e i g h t 



norma 1 

1.1 

110% 



The first example in the preceding series of rules makes the line height the same as 
the base line height of the document. The next line makes the line height 1.1 times 
greater than the base line height, as does the third, except the third uses 
percentages as a unit of measure. 

T 'P A good resource for CSS browser compatibility can be found at: 

http : //www. richinstyle.com/bugs/table. html. The site doesn't in- 
' elude IE6, but it has a good survey of all the other browsers' support for various 
CSS properties, and you really want to know how things look in older browsers 
anyway. 



Downloading Fonts Automatically 

When you write HTML, you're probably well aware that when you set up an i mg 
element in a Web document, the image downloads into the client machine's cache, 
enabling the browser to display the image. This process needs to take place if the 
image is to be viewed. An embedded font file works the same way. An embedded font 
file is a font object that you create and embed into the page using a font creation tool 
such as Microsoft's WEFT, which creates embedded fonts optimized for IE5, or 
HexMac by HexMac, which creates embedded fonts optimized for Netscape (but 
downloadable to IE5 with the use of an ActiveX Control). 

Dynamic font standards and options 

Basically, there are two font-embedding platforms: OpenType and TrueDoc. The two 
font platforms differ in some ways, the most obvious being that since they both use 
different file types, you have to jump through some hoops to develop any kind of 
font compatibility across browser platforms. 

The two formats also differ in how they appear on the screen. TrueDoc looks more 
like an image file, whereas OpenType looks more like a typeface. 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Chapter 18 ♦ Fonts 309 



OpenType 

OpenType is a font distribution standard developed by Microsoft and Adobe 
Systems, the purpose of which is to establish a means of providing some semblance 
of typography to the Web using the same kind of principles involved in font metrics 
that can be found in such type formats as PostScript and TrueType. Font metrics 
describe the metrics, or measurement, of a type character's shape using an em 
square as the basis. The em square, as mentioned earlier, is the grid upon which a 
font exists and from which its width and height are calculated. 

The technology is centered around the creation of a font object file, with an . eot 
extension, which is generated by a font creation tool either designed specifically for 
that purpose, or as an engine residing in a broader-based Web authoring program. 

One such tool, WEFT, is both a standalone application and a shared component that 
can be licensed from its developer, Microsoft, by application developers who are 
building Web-authoring software. The standalone program is free and can be found 

at http: //www. mi crosoft.com/ typography /web/ embedding/weft/. 

Currently, only Internet Explorer (versions 4 and higher) supports OpenType. 



TrueDoc 

BitStream, a typeface manufacturer, makes the competing standard TrueDoc. 
Netscape 4.0 and higher are the only browsers that directly support TrueDoc, 
although BitStream makes an ActiveX control that can be used in IE5. You can find 
more information on TrueDoc at http : //www. truedoc.com/. 



Licensing issues 



The reason font embedding has not spread more quickly across Web deployment lies 
not so much in the reluctance of Web authors to embrace the technology (although 
that's part of it), nor in the technology itself; but rather, licensing issues have slowed 
the pace of development, because font vendors are reluctant to invest in the 
development of a font only to see it distributed on Web sites without compensation. 



Should you use font embedding or style sheets? 

Many developers, in noticing the various squabbles in the realm of font embedding, 
have simply barricaded themselves from the entire affair by avoiding both platforms 
completely. As difficult as it might be to develop compatible pages using the two font 
platforms, however, you can't do any damage using them, because they rely on style 
sheets and font elements to do their work. And when they fail, they fail gracefully. 

The question of deployment then becomes a question of resources, and whether or 
not your organization has enough of them to utilize embedded fonts as part of the 
production process. 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



310 Part III ♦ Controlling Presentation with CSS 



How to add downloadable fonts to a Web page 

The two methods of font embedding have some similarities, in that both require a 
tool to create the font objects that get embedded into the Web page. The obvious 
tool of choice for IE5 developers would be WEFT, or any other tool that generates 
OpenType font files. Similarly, there are tools for TrueDoc font files that create font 
objects with a . pf r extension, which is the file extension for TrueDoc files. 



Syntax 



When you are developing OpenType files for IE5, you use an at-rule style sheet to 
establish their links: 

@font-face 1 

f ont -f ami 1 y : Garamond; 

font -styl e : normal ; 

font-weight: 700; 

src : 
url ( http : //www.myDoma i n . com/my Font Di rectory/GARAM0N3 . eot ) ; 

TrueDoc files are us ed with the 1 ink tag and the f o n t d e f attribute: 

<LINK REL= "fontdef" 

SRC="http : //www.myDomai n.com/myFontDirectory/Garamond.pfr") 

If you don't want to develop TrueDoc (PFR) files, you can work from a list of font PFR 
that are publicly available on the TrueDoc site. These and their full URLs are listed at 
the following URL: http : //www. truedoc.com/webpages/availpfrs/avail_ 
pf rs . htm. 

If you're developing for Netscape Navigator, all you need is the link element's src 
attribute. If you're developing pages for IE5, you'll need to include the ActiveX 
Control. The ActiveX control is embedded in your page with a JavaScript file located 
on the TrueDoc site: 

<SCRIPT LANGUAGE="JavaScript" 

SRC="http : //www. truedoc. com/act ivex/tdserver.js"> 
</SCRIPT> 

Put the preceding code in the head element of your HTML. 



Summary 



Here's one final argument for using CSS over the font element to style text. Even if 
you work with the largest Web site in the world, and even if stakeholders have it 
written in stone that your Web pages MUST work to the lowest common 
denominator browser, they will if you use CSS instead of the font element, and they 
won't if you use the font element over CSS. 



PI: JYS 
WY022-18 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



Chapter 18 ♦ Fonts 311 



This is because you can write basic HTML using HTML in its earliest purest form, 
and if you avoid using some of the earlier proprietary elements that began to surface 
after Netscape's popularity was at its peak, every browser in the world should be 
able to read your Web page, including text-based browsers such as Lynx. 

This chapter, aside from taking a rather strong stand on using CSS over the font 
element, covered the following: 

4- Web typography basics 

♦ Working with font styling attributes 

♦ Downloading fonts automatically 

The next chapter looks at text formatting, including indenting and aligning text, 
controlling letter and word spacing, and using text decoration such as underlines 
and blinking. 



PI: JYS 

WY022-18 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 14:58 



312 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Text Formatting 



^^ ince the Web was initially text-based and the recent push 
^^ is to make Web documents more like printed matter, it is 
no surprise that there are many styles to control text 
formatting. From simple justification to autogenerated text, 
one of CSS's major strengths is dealing with the printed word. 
This chapter covers the basics of text formatting. 



Aligning Text 

Multiple properties in CSS control the formatting of text. 
Several properties allow you to align text horizontally and 
vertically — aligning with other pieces of text or other elements 
around them. 



Controlling horizontal alignment 

You can use the text -align property to align blocks of text 
in four basic ways: left, right, center, or full. The following code 
and the output in Figure 19-1 show the effect of the 
justification settings: 



DOCT 
"htt 
tml> 
ead> 
<tit 
<sty 



YPE HTML PUBLIC "-//W3C//DTD HTML 4. 01// EK 
p : //www. w3.org/TR/html4/strict.dtd"> 



jt 



</st 
head 
ody> 
i v s 
3>Le 

cl a 
i p i s 

1 ao 



le>Text Justificati on</ti tl e> 

le type="text/css"> 

left { text-align: left; I 

right { text-align: right; 1 

center 1 text-align: center; 

full { text-align: justify; 

yle> 



tyl e="margi n : 50px"> 

ft Justified ( def aul t X/h3> 

ss="l ef t">Lorem ipsum dolor sit amet, consectetuer 

cing elit, sed diam nonummy nibh euismod tincidunt 

reet dolore magna aliquam erat volutpat. Ut wisi 







♦ ♦ ♦ ♦ 

In This Chapter 

Aligning Text 

Indenting Text 

Controlling White Space 
within Text 

Controlling Letter and 
Word Spacing 

Specifying Capitalization 

Using Text Decorations 

Formatting Lists 

Auto-Generated Text 




313 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



314 Part III ♦ Controlling Presentation with CSS 



(£3 Text Justification - Mozilla Firehird 



B@Q 



File Edit View Go Bookmarks Tools Help 



^ 



©'■*"^ .<, ISl I http://localhost/Chapter19/fig,1 9-1. html 



]v] |CVchapter19/fig1 9-2. html 



Left Justified (default) 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit obortis nisi ut aliquip ex ea commodo consequat. 

Right Justified 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 

laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 

ullamcorper suscipit obortis nisi ut aliquip ex ea commodo consequat. 

Center Justified 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 

laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 

ullamcorper suscipit obortis nisi ut aliquip ex ea commodo consequat. 

Fully Justified 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit obortis nisi ut aliquip ex ea commodo consequat. 



Done 



Figure 19-1: The four basic types of text justification. 

enim ad minim veniam, quis nostrud exerci tation ullamcorper 
suscipit obortis nisi ut aliquip ex ea commodo consequat . </p> 

<h3>Right Justifled</h3> 

<p cl ass="ri ght ">Lorem ipsum dolor sit amet, consectetuer 

adipiscing elit, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolore magna aliquam erat volutpat. Ut wisi 

enim ad minim veniam, quis nostrud exerci tation ullamcorper 

suscipit obortis nisi ut aliquip ex ea commodo consequat . </p> 

<h3>Center Justified</h3> 

<p cl ass="center">Lorem ipsum dolor sit amet, consectetuer 

adipiscing elit, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolore magna aliquam erat volutpat. Ut wisi 

enim ad minim veniam, quis nostrud exerci tation ullamcorper 

suscipit obortis nisi ut aliquip ex ea commodo consequat . </p> 



Ch3>Ful ly Justifled</h3> 

'p cl ass="f ul 1 ">Lorem ipsum dolor sit amet, 



consectetuer 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 315 



adipiscing elit, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolore magna aliquam erat volutpat. Ut wisi 

enim ad minim veniam, quis nostrud exerci tation ullamcorper 

suscipit obortis nisi ut aliquip ex ea commodo consequat . </p) 

< / d i v > 

</body> 

</html> 



Note that the default justification is left; that is, the lines in the block of text are 
aligned against the left margin and the lines wrap where convenient on the right, 
leaving a jagged right margin. 

In addition to the four standard alignment options, you can also use text-align to 
align columnar data in tables to a specific character. For example, the following 
code results in the data in the Amount Due column being aligned on the decimal 
place: 



Note 



C ! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. 01// EK 

"http://www.w3.ong/TR/html4/strict.dtd"> 
;html> 
;head> 
<title>Table Column Justification</title> 
<style type="text/css"> 

td.dec 1 text-align: "."; 1 
</style> 
;/head> 
;body> 
<table bonden="l"> 
<tn> 

<th>Customer</th> 
<th>Amount Due</th> 
</tn> 
<tn> 

<td>Acme Industries</td> 
<td class="dec">$50.95</td> 
</tn> 
<tn> 

<td>RHI LLC</td> 
<td class=-'dec">$2084.56</td> 
</tn> 
<tn> 

<td>EMrUs</td> 
<td class="dec">$0.55</td> 
</tn> 
</table> 
;/body> 
;/html> 



Columnar alignment using the text - a 1 i gn property is not well supported in 
today's user agents. You should test your target agents to ensure compliance 
before using text-al i gn this way. 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



316 Part III ♦ Controlling Presentation with CSS 



Controlling vertical alignment 

In addition to aligning text horizontally, CSS enables you to align text to objects 
around it via the vertical-align property. The vertical -align property 
supports the following values: 

4 baseline — This is the default vertical alignment; text uses its baseline to align 
to other objects around it. 

4 sub — This value causes the text to descend to the level appropriate for 

subscripted text, based on its parent's font size and line height. (This value has 
no effect on the size of the text, only its position.) 

4 super — This value causes the text to ascend to the level appropriate for 
superscripted text, based on its parent's font size and line height. (This value 
has no effect on the size of the text, only its position.) 

-4 top — This value causes the top of the element's bounding box to be aligned 
with the top of the element's parent bounding box. 

4 text-top — This value causes the top of the element's bounding box to be 
aligned with the top of the element's parent text. 

4 middle — This value causes the text to be aligned using the middle of the text 
and the mid-line of objects around it. 

4 bottom — This value causes the bottom of the element's bounding box to be 
aligned with the bottom of the element's parent bounding box. 

4 text-bottom — This value causes the bottom of the element's bounding box to 
be aligned with the bottom of the element's parent text. 

4 length — This value causes the element to ascend (positive value) or descend 
(negative value) by the value specified. 

4 percentage — This value causes the element to ascend (positive value) or 
descend (negative value) by the percentage specified. The percentage is 
applied to the line height of the element. 

The following code and the output in Figure 19-2 shows the effect of each value: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<ti tl e>Verti cal Text Al i gnment</ti tl e> 
<style type="text/css"> 

.baseline 1 vertical-align: baseline; ) 
.sub 1 vertical-align: sub; 1 
.super 1 vertical-align: super; 1 
.top 1 vertical-align: top; 1 
.text-top 1 verti cal -al i gn : text-top; ) 
.middle { vertical-align: middle; ) 
.bottom { vert i ca 1 -a 1 i gn : bottom; 1 
.text-bottom 1 verti cal -al i gn : text-bottom; 1 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 317 



^J Vertical Text Alignment - Microsoft Internet Explorer 



- n0 



File Edit View Favorites Tools Help 



# 



o-o-aaft'p**^ 



0- a s * 



Address jQ http://localhost/Chapterl9/figl9-2.htnnl 



[Baseline: Parent F^T^] text 



|Sub: Parent r^— n^] text 



|Super: Parent ^^^ text 



[Top: Parent l-^-'H text 



[Text-top Parent to" l '=l texT 



[Middle: Parent I<ij«ikj text 



(Bottom: Parent [^n^n-j text 



[Text-bottom: Parent [,i„„n,^ text 



[Length: Parent togl*^ text 



Percentage: Parent 1 1 ^ 1 t _j text 



flDone 



*| 



* j Local intranet 



Figure 19-2: The effect of various vertical-align settings. Borders were added to 
the text to help contrast the alignment. 



length { verti cal -al i gn : .5em; ) 
percentage { vertical -align: -50%; 
/* All elements get a border */ 
body * { border: lpx solid black; 
/* Reduce the spans' font by 50% 7 
p * { font-size: 50%; 1 
tyle> 



Baseline: Parent 

span cl ass="basel i ne">al i gned text</span> text</p> 

Sub: Parent 

span cl ass="sub">al i gned text</span> text</p> 

Super: Parent 

span cl ass="super">al i gned text</span> text</p> 

Top: Parent 

span cl ass="top">al i gned text</span> text</p> 

Text-top Parent 

span cl ass="text -top">a 1 i gned text</span> text</p> 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



318 Part III ♦ Controlling Presentation with CSS 



<p>Middle: Parent 

<span cl ass="mi ddl e">al i gned text</span> text</p> 
<p>Bottom: Parent 

<span cl ass="bottom">al i gned text</span> text</p> 
<p>Text -bottom: Parent 

<span cl ass="text -bottom">al i gned text</span> text</p> 
<p>Length: Parent 

<span cl ass="l ength">al i gned text</span> text</p> 
<p>Percentage : Parent 

<span cl ass="percentage">al i gned text</span> text</p> 
</body> 
</html> 

Of course, text isn't the only element affected by an element's vertical -align 
setting — all elements that border the affected element will be aligned appropriately. 
Figure 19-3 shows an image next to text. The image has the vertical -align 
property set to middle. Note how the midpoint of both elements is aligned. 



) Vertical Image Alignment - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



Address , : . . http : //localhost/Chapter 1 9/figl 9-3 . html 



BB< 



J 



Spherical Products 



*j Local intranet 



Figure 19-3: The verti cal -al i gn property can be used to vertically 
align most elements. 



Indenting Text 



You can use the text- indent property to indent the first line of an element. For 
example, to indent the first line of a paragraph of text by 25 pixels, you could use 
code similar to the following: 

<p styl e="text - i ndent : 25px;"> Lorem ipsum dolor sit amet, 
Consectetuer adipiscing el it, sed diam nonummy nibh euismod 
tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut 
wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit obortis nisi ut aliquip ex ea commodo 
consequat . </p> 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 319 



Note that the text- indent property only indents the first line of the element. If you 
want to indent the entire element, use the ma rgi n properties instead. 

See Chapter 20 for more information about the ma rgi n properties. 




You can specify the indent as a specific value (1 i n , 2 5 p x, and so on), or as a percentage 
of the containing block width. Note that when specifying the indent as a percentage, 
the width of the user agent's display will play a prominent role in the actual size 
of the indentation. Therefore, when you want a uniform indent, use a specific value. 



Controlling White Space within Text 

White space is typically not a concern in HTML documents. However, at times you'll 
want better control over how white space is interpreted and how certain elements 
line up to their siblings. 



Clearing floating objects 



The float property can cause elements to ignore the normal flow of the document 
and "float" against a particular margin. For example, consider the following code and 
resulting output shown in Figure 19-4: 



;idoctyp 

"http: 
Chtml > 

;head> 
<title 

;/head> 

;body> 
<p><b> 
< i m g s 
Lorem 
a d i p i s 
ut 1 ao 
e n i in a 
ul 1 amc 
conseq 



E HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 
//www. w3.org/TR/html4/strict.dtd"> 



■Floating Image</ti tl e> 



Floating Image</bXbr> 

rc="sphene . png" styl e="float : right;") 

ipsum dolor sit amet, consectetuer 

cing el it, sed diam nonummy nibh euismod tincidunt 

reet dolore magna aliquam erat volutpat. Ut wisi 

d minim veniam, quis nostrud exerci tat ion 

orper suscipit obortis nisi ut aliquip ex ea commodo 

uat . </p> 



<p><b>Non-Floating Image</bXbr> 

<img src="sphere . png"> 

Lorem ipsum dolor sit amet, consectetuer 

adipiscing el it, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolore magna aliquam erat volutpat. Ut wisi 

enim ad minim veniam, quis nostrud exerci tat ion 

ullamcorper suscipit obortis nisi ut aliquip ex ea commodo 

consequat . </p> 

;/body> 

;/html> 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



320 Part III ♦ Controlling Presentation with CSS 



@ Floating Image - Microsoft Internet Explorer 



b®b 



File Edit View Favorites Tools Hel|> 

O'Ofl \H ft I P & tf © I 0- 



i 



■ $ 



Address ^ http://localhost/Chaptei-19/figl9-4,html 



EIH' 



Floating linage 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diarn 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat 
volutpat Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit obortis nisi ut aliquip ex ea commodo consequat. 

Non-Floating linage 





Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diarn 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi 
enim ad minim veriam, quis nostrud exerci tation ullamcorper suscipit obortis nisi ut 
aliquip ex ea cornrnodo consequat. 



*j Local intranet 



Figure 19-4: Floating images can add a dynamic feel to your documents. 

Although floating images can add an attractive, dynamic air to your documents, their 
placement is not always predictable. As such, it's helpful to be able to tell certain 
elements not to allow floating elements next to them. One good example of when you 
would want to disallow floating elements is next to headings. For example, consider 
the document shown in Figure 19-5. 

Using the clear property you can ensure that one side or both sides of an element 
remain free of floating elements. For example, adding the following style to the 
document in Figure 19-5 ensures that both sides of all heading levels are clear of 
floating elements — this results in the display shown in Figure 19-6. 

hl,h2,h3,h4,h5,h6 { clear: both; ) 

You can specify 1 eft, right, both, or none (the default) for values of the clear 
property. Note that the clear property doesn't affect the floating element. Instead, 
it forces the element containing the clear property to avoid the floating 
element(s). 



The white-space property 



User agents typically ignore extraneous white space in documents. However, at 
times you want the white space to be interpreted literally, without having to result to 
using a <pre> tag to do so. Enter the white- space property. 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 321 



@ Floating Image - Microsoft Internet Explorer 



staia 



File Edit View Favorites Tools Help 



O'Q-0laS6P*«e|0i 



m $ 



Address |£] http://localhost/Chapterl9/figl9-5.html 



HH'so 




Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat 
volutpat. 



2.1 



Heading 1 



Lorem ipsurn dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullamcorper suscipit obortis nisi ut aliquip ex ea 
commodo consequat. 



HjDone 



\J Local intranet 



Figure 19-5: Floating images can sometimes get in the way of other 
elements, as in the case of this heading. 



@ Preventing Floating Image - Microsoft Internet Explorer 



BOB 



File Edit View Favorites Tools Help 

©to a a & I p * * © 



B $ 



Address @ http://localho5t/Chapterl9/figl9-6.html 



_ :go 




Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat 
volutp at. 



Heading 1 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullamcorper suscipit obortis nisi ut aliquip ex ea 
commodo consequat. 



*J Local intranet 



-i 



g]Done 



Figure 19-6: Using the cl ear property forces an element to start past 
the floating element's bounding box (and before any additional floating 
elements begin). 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



322 Part III ♦ Controlling Presentation with CSS 



The whi te- space property can be set to the following values: 

♦ normal 

♦ pre 

♦ nowrap 

The default setting is norma 1 , that is, ignore extraneous white space. 

If the property is set to pre, text will be rendered as though it were enclosed in a 
<pre> tag. Note that using pre does not affect the font or other formatting of the 
element — it only causes white space to be rendered verbatim. For example, the 
following text will be spaced exactly as shown in the following code: 

<p styl e="whi te-space : pre;">This paragraph's words 

are 
irregularly spaced, but will be rendered as 

such 
by the user agent. </p> 

Setting the whi te-space property to nowrap causes the element not to wrap at the 
right margin of the user agent. Instead, it continues to the right until the next explicit 
line break. User agents should add horizontal scroll bars to enable the user to fully 
view the content. 



Controlling Letter and Word Spacing 

The letter- spacing and word- spacing properties can be used to control the 
letter and word spacing in an element. Both elements take an explicit or relative 
value to adjust the spacing — positive values add more space, and negative values 
remove space. For example, consider the following code and output in Figure 19-7: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>Letter Spacing</title> 

<style type="text/css"> 

.normal { 1 etter -spaci ng : normal; 1 
.tight { 1 etter -spaci ng : -.2em; I 
.loose { 1 etter -spaci ng : .2em; 1 

</style> 
</head> 
<body> 

<h3>Normal</h3> 

<p cl ass = "normal ">Lorem ipsum dolor sit amet, consectetuer 

adipiscing el it, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolore magna aliquam erat volutpat. Ut wisi 

enim ad minim veniam, quis nostrud exerci tation 

ullamcorper suscipit obortis nisi ut aliquip ex ea commodo 

consequat . </p> 

<h3>Tight</h3> 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 323 



<p cl a 

a d i p i s 
ut 1 ao 
e n i m a 
ul 1 amc 
conseq 
<h3>Lo 
<p cl a 
a d i p i s 
ut 1 ao 
e n i m a 
ul 1 amc 
conseq 
;/body> 
;/html> 



ss= 
ci n 
ree 
d m 
orp 
uat 
ose 
ss= 
ci n 
ree 
d m 
orp 
uat 



"tight 
g el it 

t dol o 
i n i m v 
er sus 
.</p> 
</h3> 
"loose 
g el it 
t dol o 
i n i m v 
er sus 
.</p> 



">Lorem ipsum dolor sit amet, consectetuer 
, sed diam nonummy nibh euismod tincidunt 
re magna aliquam erat volutpat. Ut wisi 
eniam, quis nostrud exerci tat ion 
cipit obortis nisi ut aliquip ex ea commodo 



">Lorem ipsum dolor sit amet, consectetuer 
, sed diam nonummy nibh euismod tincidunt 
re magna aliquam erat volutpat. Ut wisi 
eniam, quis nostrud exerci tat ion 
cipit obortis nisi ut aliquip ex ea commodo 



^ Letter Spacing - Microsoft Internet Explorer 



_ H0 



File Edit View Favorites Tools Hel|> 

G T © - S 12] i: P ir. * « 



i- a m $ 



Address Q http://localhost/Chapterl9/f igl9-7.html 



If 

3B Gq 



Noiiti.il 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullamcorper suscipit obortis nisi ut aliquip ex ea 
commodo consequat 

Tight 



Loose 

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, 
sed diam nonummy nibh euismod tincidunt ut laoreet dolore 
magna aliquam erat volutpat. Ut wisi enim ad minim veniam, 
quis nostrud exerci tation ullamcorper suscipit obortis nisi 
ut aliquip ex ea commodo consequat. 



©Done 






*j Local intranet 



*i 



Figure 19-7: The letter-spacing property does exactly as its name 
indicates, adjusts the spacing between letters. 

Note that the user agent can govern the minimum amount of letter spacing allowed- 
setting the letter spacing to too small a value can have unpredictable results. 



The word -spacing property behaves exactly like the letter- spacing property, 
except that it controls the spacing between words instead of letters. Like 
letter- spacing, using a positive value with word -spacing results in more 
spacing between words, and using a negative value results in less spacing. 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



324 Part III ♦ Controlling Presentation with CSS 



Specifying Capitalization 

Styles can also be used to control the capitalization of text. The text-transform 
property can be set to four different values, as shown in the following code and 
Figure 19-8: 



|T) Letter Spacing - Microsoft Internet Explorer 



B@B 



File Edit View Favorites Tools Help 

o - e - b si &\p * * e I e ~ & b a 



l! 



Address 



|http://localho5r/Chapterl9/figl9-8,hrml 



TvjgjGo 



Normal 

Lorem ipsum DOLOR sit amet, consectetuer adipiscing elit, SED diam nonummy nibh 
euismod tincidunt ut laoreet doLore magna ALIQUAM erat volutpat. 

Initial Cups 

Lorem Ipsum DOLOR Sit Amet, Consectetuer Adipiscing Elit, SED Diam Nonummy 
Nibli Euismod Tincidunt Ut Laoreet DoLore Magna ALIQUAM Erat Volutpat. 

Uppercase 

LOREM IPSUM DOLOR SET AMET, CONSECTETUER ADIPISCING ELIT, SED 
DIAM NONUMMY NTBH EUISMOD TINCIDUNT UT LAOREET DOLORE 
MAGNA ALIQUAM ERAT VOLUTPAT. 

Lowercase 

lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod 
tincidunt ut laoreet dolore magna aliquam erat volutpat. 






g]Dcri, 



*j Local intranet 



Figure 19-8: The text-transform property allows you to influence the 
capitalization of elements. 



DOCTY 
"http 
tml> 
ead> 
<titl 
<styl 
. no 
. i n 
. up 
.lo 
</sty 
head) 
ody> 



PE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 
: //www. w3.org/TR/html4/strict.dtd"> 



e>Letter Spacing</title> 

e type="text/css"> 

rmal { text -transform: none; ) 

itcaps 1 text -transform : capitalize; 

per { text -transform; uppercase; I 

wer 1 text -transform: lowercase; I 

le> 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 325 



h3> 

P c 
di p 
t 1 
h3> 
P c 
ons 
i nc 
ol u 
h3> 
P c 
di p 
t 1 
h3> 
P c 
di p 
t 1 
ody 
tml 



Normal </h3> 

1 ass="normal ">Lorem ipsum DOLOR sit amet, consectetuer 

iscing el it, SED diam nonummy nibh euismod tincidunt 

aoreet doLore magna ALIQUAM erat vol utpat . </p> 

Initial Caps</h3> 

1 ass="i ni tcaps">Lorem ipsum DOLOR sit amet, 

ectetuer adipiscing el it, SED diam nonummy nibh euismod 

idunt ut laoreet doLore magna ALIQUAM erat 

tpat . </p> 

Uppercase</h3> 

1 ass="upper">Lorem ipsum DOLOR sit amet, consectetuer 

iscing el it, SED diam nonummy nibh euismod tincidunt 

aoreet doLore magna ALIQUAM erat vol utpat . </p> 

Lowercase</h3> 

1 ass="l ower">Lorem ipsum DOLOR sit amet, consectetuer 

iscing el it, SED diam nonummy nibh euismod tincidunt 

aoreet doLore magna ALIQUAM erat vol utpat . </p> 



Note that there are s ome rules as to what text-transform will and won't affect. 
For example, the capitalize value ensures that each word starts with a capital 
letter, but it doesn't change the capitalization of the rest of the word. Setting the 
property to no rma 1 will not affect the capitalization of the element. 



Using Text Decorations 



You can add several different effects to text through CSS. Most are accomplished via 

the text-decoration and text -shadow properties. 

The text-decoration property allows you to add the following attributes to text: 

4- underline 

♦ overline (line above text) 

♦ line-through 

♦ blink 

As with most properties, the values are straightforward: 

<p styl e="text -decorati on : none;">No Decorati on</p> 

<p styl e="text -decorati on : underl i ne ; ">Underl i ned</p> 

<p styl e="text -decorati on : overl i ne ; ">0verl i ned</p> 

<p styl e="text -decorati on : 1 i ne-through ; ">Li ne Through</p> 

<p styl e="text -decorati on : bl i nk ; ">B1 i n k</p> 

The text -shadow property is a bit more complex, but can add stunning drop 
shadow effects to text. The text-shadow property has the following format: 

text-shadow: "[color] hori zontal -di stance 
verti cal -di stance [blur]" 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



326 Part III ♦ Controlling Presentation with CSS 



The property takes two values to offset the shadow, one horizontal, the other 
vertical. Positive values set the shadow down and to the right. Negative values set 
the shadow up and to the left. Using combinations of negative and positive settings, 
you can move the shadow to any location relative to the text it affects. 

The optional color value sets the color of the shadow. The blur value specifies the 
blur radius — or the width of the effect — for the shadow. Note that the exact 
algorithm for computing the blur radius is not specified by the CSS specification — as 
such your experience may vary with this value. 

The text-shadow property allows multiple shadow definitions, for multiple shadows. 
Simply separate the definitions with commas. 

The following code creates a drop shadow on all < h 1 > headlines. The shadow is set 
to display above and to the right of the text, in a gray color. 

hi { text -shadow: #666666 2em -2em; ) 

The following definition provides the same shadow as the previous example, but 
adds another, lighter gray shadow directly below the text: 

hi i text-shadow: #666666 2em -2em, #AAAAAA Oem 2em; I 

Unfortunately, not many user agents support text -shadow. If you want such an 
effect, you might be better off creating it with a graphic instead of text. 



Formatting Lists 



Several CSS properties modify lists. You can change the list type, the position of the 
elements, and specify images to use instead of bullets. The list-related properties are 
covered in the following sections. 



An overview of lists 

There are two types of lists in standard HTML, ordered and unordered. Ordered lists 
have each of their elements numbered and are generally used for steps that must 
followed a specific order. Unordered lists are typically a list of related items that do 
not need to be in a particular order (commonly formatted as bulleted lists). 

Cross- A Lists are covered in more detail in Chapter 5. 
Reference 




Ordered lists are enclosed in the ordered list or <ol > tag. Unordered lists are 
enclosed in the unordered list or <ul > tag. A list item tag (<1 i >) precedes each item 
in either list. The following code shows short examples of each type of list. 
Figure 19-9 shows the output of this code. 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 327 



(ol>An ordered list 

<li>Step 1 

<li>Step 2 

<li>Step 3 
(/ol> 
<ul >An unordered 1 i st 

<li>Item 1 

<li>Item 2 

<li>Item 3 
(/ul> 



jj List Samples - Microsoft Internet Explorer 



- n;S 



File Edit View Favorites Tools Help 



* a b -a 



Address @ http://localhc.st/Chapterl9/figl9-9.html 



EB< 



An ordered list 

1. Step 1 

2. Step 2 

3. Step 3 

An unordered list 

• Item 1 

• Item 2 

• Item 3 



1 Done 



*J Local intranet 



Note 



Figure 19-9: An example of an ordered and unordered list. 

CSS lists— any element will do 

An important distinction with CSS lists is that you don't need to use the standard list 
tags. CSS supports the 1 i st- i tern value of the display property, which, in effect, 
makes any element a list item. The < 1 i > tag is a list item by default. 

There is a list style shortcut property that you can use to set list properties with 
one property assignment. You can use the list-style property to define the other 
list properties, as follows: 



list-style: <7 / st-styl e-type> 
< / 7 st-styl e- image> 



'.list-style-position') 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



328 Part III ♦ Controlling Presentation with CSS 



For example, to create a new list item you can define a class as a list item using the 
display property: 

.item 1 display: list-item; I 

Thereafter, you can use that class to declare elements as list items: 

<p cl ass="i tem">Thi s is now a list item</p> 

As you read through the rest of this section, keep in mind that the list properties can 
apply to any element defined asa list- item. 

Note Both bullets and numbers preceding list items are known as markers. Markers 

have additional value with CSS, as shown in the Generated content section later 
in this chapter. 



List style type 



The 1 i st - styl e - type property is used to set the type of the list and, therefore, 
what identifier is used with each item — bullet, number, roman numeral, and so on. 

The 1 i st- styl e- type property has the following valid values: 

4 disc 

♦ circle 

4 square 

4 decimal 

4 decimal-leading-zero 

4 lower-roman 

4 upper-roman 

4 lower-greek 

4 lower-alpha 

4 lower-latin 

4 upper-alpha 

4 upper-latin 

4 hebrew 

4 armenian 

4 georgian 

4 cjk-ideographic 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 329 



♦ hiragana 

♦ katakana 

4- hiragana-iroha 

♦ katakana-iroha 

♦ none 



The values are all fairly mnemonic; setting the style provides a list with appropriate 
item identifiers. For example, consider this code and the output shown immediately 
after: 



HTML Code: 

<ol style="list-style-type:lower-roman; 

A Roman Numeral List 

<li>Step 1 

<li>Step 2 

<li>Step 3 
</ol> 



Output: 

A Roman Numeral List 
i . Step 1 
ii. Step 2 
ill. Step 3 

You can use the none value to suppress bullets or numbers for individual items. 
However, this does not change the number generation, the numbers are just not 
displayed. For example, consider the following revised code and output: 

HTML Code: 

<ol style="list-style-type:lower-roman;"> 

A Roman Numeral List 

<li>Step 1 

<li styl e="l i st -styl e -type : none ; ">Step 2 

<li>Step 3 
</ol> 



Output: 

A Roman Numeral List 
i . Step 1 
Step 2 
ill. Step 3 

Note that the third item is still number 3, despite suppressing the number on 
item 2. 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



330 Part III ♦ Controlling Presentation with CSS 



Positioning of markers 

The list-style-position property can change the position of the marker in 
relation to the list item. The valid values for this property are i nside or outside. 
The outside value provides the more typical list style, where the marker is offset 
from the list item and the entire text of the item is indented. The i nside value sets 
the list to a more compact style, where the marker is indented with the first line of 
the item. Figure 19-10 shows an example of both list types: 



] List Samples - Microsoft Internet Exploiei 



BOB 



File Edit View Favorites Tools Help 

Q - O - E E <i P * » « 



0- & m 



Address £] http://localhost/Chapterl9/figl9-10,htrnl 



aa< 



An "Outside" List 

Lorem. ipsum dolor sit arnet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad 
minim veniam, quis nostrad exerci tation ullamcorper suscipit obortis nisi ut aliquip 
ex ea cornmodo cons equal. 

An "Inside" List 

1. Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed diam nonummy 
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim 
ad minim veniam, quis nostrud exerci tation ullamcorper suscipit obortis nisi ut 
aliquip ex ea commodo consequat. 






-I 



j£)Done 



\j Local intranet 



Figure 19-10: The difference between inside and outside positioned lists. 



Images as list markers 



You can also specify an image to use as a marker using the 1 i s t - s ty 1 e - i ma ge 
property. This property is used instead of the 1 i st-styl e- type property, 
providing a bullet-like marker. You specify the image to use with the u rl construct. 
For example, the following code references sphere.jpg and cone . j pg as images to 
use in the list. The output is shown in Figure 19-11. 



(oi: 



<li styl e="l i st -styl e - image : url ( sphere . j pg ) ' 
Lorem ipsum dolor sit arnet, consectetuer 



PI: JYS 
WY022-19 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 33 1 



adipiscing el it, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolore magna aliquam erat volutpat. 

<li styl e="l i st -styl e - image : url ( cone . jpg ) "> 

Lonem ipsum dolor sit amet, consectetuen 

adipiscing el it, sed diam nonummy nibh euismod tincidunt 

ut laoreet dolone magna aliquam enat volutpat. 

;/oi> 



] List Images - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



* 



o - a - a b ft : p 



& * a ■ -a 



I ht tp : //localhost/Chaptei-1 9/fig 1 9- 1 1 .html 



•Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. 



m 



"iLorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. 



-I 



\* Local intranet 



Figure 19-1 1 : You can use images as list markers, such as the sphere and cone 
shown here. 



Note that you can use any URL-accessible image with the 1 i st- styl e- i mage. 
However, it is important to use images sized appropriately for your lists. 



Auto-generated Text 



CSS has a few mechanisms for autogenerating text. Although this doesn't fit in well 
with the presentation-only function of CSS, it can be useful to have some constructs 
to automatically generate text for your documents. 



Note 



You can do much more with autogenerated content than is shown here. Feel 
free to experiment with combining pseudo-elements (covered in Chapter 17) 
and other autogenerated text constructs (listed with other CSS elements in 
Appendix B). 



Specifying quotation marks 



You can use the autogeneration features of CSS to define and display quotation 
marks. First, you need to define the quotes, and then you can add them to elements. 

The quotes property takes a list of arguments in string format to use for the open 
and close quotes at multiple levels. This property has the following form: 



quotes: <open_flrst_l evel > <cl ose_first_l evel ; 
<open_second_l evel > <cl ose_second_l evel > .. 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



332 Part III ♦ Controlling Presentation with CSS 



- 



The standard definition for most English uses is as follows: 

quotes: ; 

This specifies a double-quote for the first level (open and closing) and a single-quote 
for the second level (open and closing). Note the use of the opposite quote type 
(single enclosing double and vice versa). 



Note Many browsers do not support autogenerated content. 



Once you define the quotes, you can use them along with the : b e f o r e and : a f t e r 
pseudo-elements, as in the following example: 

bl ockquote : before { content: open-quote; ) 
bl ockquote : after { content: close-quote; ) 

The open-quote and close-quote words are shortcuts for the values stored in 
the quotes property. Technically, you can place just about anything in the content 
property because it also accepts string values. The next section shows you how you 
can use the content property to create automatic counters. 

Note When using string values with the content property, be sure to enclose the string 

in quotes. If you need to include newlines, use the \A placeholder. 



Numbering elements automatically 

One of the nicest features of using the content property with counters is the ability 
to automatically number elements. The advantage of using counters over standard 
lists is that counters are more flexible, enabling you to start at an arbitrary number, 
combine numbers (for example, 1.1), and so on. 

Note Many user agents do not support counters. Check the listings in Appendix B for 

more information on what user agents support what CSS features. 

The counter object 

A special object can be used to track a value and can be incremented and reset by 
other style operations. The counter object has this form when used with the 
content property, as in the following: 

content: counter ( counter_name) ; 

This has the effect of placing the current value of the counter in the content object. 
For example, the following style definition will display "Chapter" and the current 
value of the "chapter" counter at the beginning of each < h 1 > element: 

hl:before { content: "Chapter " counter ( chapter ) " "; ) 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



Chapter 19 ♦ Text Formatting 333 



Of course, it's of no use to always assign the same number to the : bef o re 

pseudo-element. That's where the counter- i increment and counter- reset 
objects come in. 

Changing the counter value 

The counter- i ncrement property takes a counter as an argument and increments 
its value by one. You can also increment the counter by other values by specifying 
the value to add to the counter after the counter name. For example, to increment 
the chapter counter by 2, you would use this definition: 

counter - i ncrement : chapter 2; 



y 



T 'P You can increment several counters with the same property statement by spec- 

ifying the additional counters after the first, separated by spaces. For example, 
the following definition will increment the chapter and section counters each 
by 2: 

counter - i ncrement : chapter 2 section 2; 

You can also specify negative numbers to decrement the counter(s). For example, to 
decrement the chapter counter by 1, you could use the following: 

counter - i ncrement : chapter -1; 

The other method for changing a counter's value is by using the counter-reset 
property. This property resets the counter to zero or, optionally, an arbitrary number 
specified with the property. The counter- reset property has the following format: 

counter - reset : counter_nante [value]; 
For example, to reset the chapter counter to 1, you could use this definition: 

counter- reset : chapter 1; 



T 'P You can reset multiple counters with the same property by specifying all the 

counters on the same line, separated by spaces. 

Note that if a counter is used and incremented or reset in the same context (in the 
same definition), the counter is first incremented or reset before being assigned to a 
property or otherwise used. 



Chapter and section numbers 

Using counters, you can easily implement an auto-numbering scheme for chapters 
and sections. To implement this auto-numbering, use <hl> elements for chapter 
titles and <h2> elements for sections. We will use two counters, chapter and section, 
respectively. 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



334 Part III ♦ Controlling Presentation with CSS 



First, you need to set up your chapter heading definition, as follows: 

hl:before {content: "Chapter " counter(chapter) ": "; 
counter-increment: chapter; 
counter-reset: section; ) 

This definition will display "Chapter chapterjium:" before the text in each < h 1 > 
element. The chapter counter is incremented and the section counter is 
reset — both of these actions take place prior to the counter and text being assigned 
to the content property. So, the following text would then result in the output 
shown in Figure 19-12: 



<hl>First Chapter</hl> 
<hl>Second Chapter</hi; 
<hl>Third Chapter</hl> 



& Chapter Ante -Number - Opera 



B3B 



Q File Edit View Navigation Bsokmcrlio Vbil Wirdow Hob 



5 >. 



z f 



I B htt p : //I o c a I h o st.'Ch s pte n* 9/fig ' 9- 1 2. M ml 



. 100% - 



Chapterl ; First Chapter 
Chapter2: Second Chapter 
Chapter3: Third Chapter 



Figure 19-12: Auto-numbering <hl> elements. 



The next step is to set up the section numbering, which is similar to the chapter 
numbering: 



h2:before {content: "Section " counter(chapter) "." 
counter(section) ": "; 
counter- increment: section; 

Now the styles are complete. The final following code results in the display shown in 
Figure 19-13: 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 



8:49 



Chapter 19 ♦ Text Formatting 335 



;idoct 

"htt 
Chtrnl) 

;head> 

<tit 

<sty 

hi 



YPE HTML PUBLIC "-//W3C//DTD HTML 4. 01// EK 
p : //www. w3.org/TR/html4/strict.dtd"> 



le>Chapter Auto -Number</t i tl e> 
le type="text/css"> 

:before {content: "Chapter " counter ( chapter ) 
counter- i ncrement : chapter; 
counter-reset: section; ) 
h2:before {content: "Section " counter(chapter) 
counter(section) ": "; 
counter- i ncrement : section; I 



</st 

;/head 

;body> 

<hl> 

<h 

<h 

<hl> 

<h 

<hl> 

;/body 

;/html 



yle> 



First Chapter</hl> 
2>Section Name</h2> 
2>Section Name</h2> 
Second Chapter</hl> 
2>Section Name</h2> 
Third Chapter</hl> 



| <Q Chapter Aiito-Hiimher - Up&ra 



EBIQ 



D File Frit View MawgsT nn ^mkmarkf Mai Winrhw H=p 



I j n1t3:A'localhoot'Chapt3ria'fig19 '3.i:nl 

Chapter 1: First Chapter 

Section 1.1: Section IName 
Section 1.2: Section Name 

Chapter 2: Second Chapter 

Section 2.1 Section Name 

Chapter 3: Third Chapter 



[ - IQj 100% - 



Figure 19-13: The completed auto-numbering system does both chapters 
and sections. 



T 'P The counters should automatically start with a value of 0. In this example, that 

\ is ideal. However, if you need to start the counters at another value, you can 
attach resets to a higher tag (such as <body>), as in the following example: 

body:before {counter- reset : chapter 12 section 10;} 



PI: JYS 

WY022-19 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:49 



336 Part III ♦ Controlling Presentation with CSS 



Custom list numbers 

You can use a similar construct for custom list numbering. For example, consider the 
following code, which starts numbering the list at 20: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<title>List Auto-Number</title> 
<style type="text/css"> 

li:before Icontent: counter(list) ": "; 
counter - i increment : list; I 
</style> 
</head> 
<body> 

<ol styl e="counter - reset : list 19; 
1 ist-style-type:none;"> 
<li> First item 
<li>Second item 
<li>Third item 
</ol> 
</body> 
</html> 

Note that the <ol > tag resets the counter to 19 due to the way the counte r - 

i nc rement works (it causes the counter to increment before it is used). So you must 

set the counter one lower than the first occurrence. 

T 'P You can have multiple instances of the same counter in your documents, and 

they can all operate independently. The key is to limit each counter's scope: A 
counter's effective scope is within the element that initialized the counter with 
the first reset. In the example of lists, it is the <ol > tag. If you nested another 
<ol > tag within the first, it could have its own instance of the list counter, 
and they could operate independently of each other. 



Summary 



This chapter covered basic text formatting with CSS. You learned how to justify and 
align text, as well as control most other aspects of text layout. As you continue to 
learn CSS, you will see that the considerable information presented here barely 
scratches the surface of the capabilities of CSS. The next few chapters deal with 
particular elements and specific uses of CSS — however, it is when you use all of the 
capabilities together that CSS really shines. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



Padding, 
Margins, and 
Borders 



The CSS formatting model places every element within 
a layer of boxes, each layer customizable by styles. This 
chapter introduces the box formatting model and its individual 
pieces — padding, borders, and margins. You learn how each is 
defined and manipulated by CSS. 



Understanding the Box 
Formatting Model 



C H 



CSS uses the box formatting model for all elements. The box 
formatting model places all elements within boxes — rectangles 
or squares — that are layered with multiple, configurable 
attributes. 



Note 



Box layout and formatting models have been used in 
traditional publishing for ages. Open any magazine or 
newspaper and you will see box layout in action— the 
headline within one box, columns of text in their own 
boxes, ads in boxes, and so on. 

Figure 20-1 shows a typical Web page. Although the design 
doesn't seem too boxy, if you turn on borders for all elements 
you can see how each element is contained in a rectangle or 
square box. Figure 20-2 shows the same Web page with 
borders around each element. 

Within each CSS box you have control over three different, 
layered properties: 

♦ Margins — Represent the space outside of the element, the 
space that separates elements from one another. 




♦ ♦ ♦ ♦ 

In This Chapter 

Understanding the Box 
Formatting Model 

Defining Element Margins 

Adding Padding Within 
an Element 

Adding Borders 

Using Dynamic Outlines 

♦ ♦ ♦ ♦ 



337 



P1:KTX 

WY022-20 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



|^| HunditheUa-i -Hkn^ott Internet Lxplorer 


EEiij 


HI* Frllr Wew rnv.irlTfifi To.Br.li Hfil|k 

o ■■'-■ o - a a fi Pit «|e-aE-i 


* 



: , 1 "!oc=|-:0£:tj'Z?-![:p:=f^o:pl E-n:b:rd/ 




.> 



v l„. p. 



<■„.,■ .' » I IP I, AL ■ I. I 



P I, H, H T h r B A G 



O p i k e d Punch 

09 fabeugp* 2004 



n Ihe Onaker 


WeditesdnVj April 1, -JXiW-S 

Durriuurdl^ Burub CiviNdiii Tuu; Lul't -= M Lt. lTuli rrurdl 
sclf-richicous "hitc horses. "temamDD' :hc temting nf 
V jrjn^ ■w .-? Hr>n .iit i frvy _ irlhir^ --mm .i n n n nf lihnrr 
^n.ri=^: II ntm K!inhT= uVaTii -=;i Jinin ^ -v ^rr Amnfist 1 ., 


-fijp f:«- 1U - Mo-± J: 
'* Mol'at Nd ! , Just 


IilLiuUun^l. 


VfPF.r.tr.fyTw, : fh^t^ry ', >YJf/f>) Ahrmf *j& t r tiir.{ir=!'7 r./vfipp 



Y-jjKs'as'a 'a:t \<>za.; hitir-.sn ^.'q'fts Water, ss^ ,r. a rtE-w 



From /^l: 

i '.7 t-'r&F.iri&r. f /ii 1 '. ( A- T.r. j, i* "ifi'vi rt*= //AH.' hnrr.r.'.nt} nf r.f-igr^'i'i 
r.r fr.f- TT.rr-iiF. fr.nf ri ntT. ?w?^ rrrr; fhr.Y^ r.!ttr.xi/wj wr.iii/i 
.re s *.rxDi-a' a<fj sr.st=-3'c aisastw r . ^riiT.s Mr./srer Tz«-ty ctar 
ct r.^e I'r./raJ ft'TgcfDrn (<JK, la.ti, T'? 1 ; ■; a just a- a.-, base J net 
or ib/'.ij'iai aiiib'irjrm b^!. lv. r-d.'t-'eo / F;<=f/.ot. ?; va'd^'il 

: 3-. -.--V ■."■■ S>. ■. '■«.' '»T ■ -'••7' ■ '.■'■ rf i ' V -.■' '■- ' V ■•■■ 




■* 



s^ 



Figure 20-1 : A typical Web page that isn't overtly boxy in design. 



Fl ^ 


iiclitheLiaq -Mfc nwott Internet L :■: p 1 m r*r 






BUS 


rile 

- 


Frllr View ravarlTea Too la Help 

O^j I A P -t m e 


- 


a b ■* 


* 


Adore* 


h::::.'. , locEhffitj'JiEp:Era). , PTE-b:rdf 






HD=" 




Figure 20-2: The same Web page with borders around all elements, clearly showing the 
box formatting model. 



338 



P1:KTX 

WY022-20 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



Chapter 20 ♦ Padding, Margins, and Borders 339 

♦ Borders — Configurable lines inside the elements margins, but outside of the 
element's padding (defined next). 

♦ Padding — The space between the element and the element's border. 
Figure 20-3 shows a visual representation of how these properties relate. 



Margin 



Padding 



Border 




Figure 20-3: How the margin, border, padding, and actual 
element relate to each other spatially. 



Each of these properties can be separately configured, but can also work well 
together to uniquely present an element. 



Defining Element Margins 



Margins are an important issue to consider when designing documents. Some 
elements have built-in margins to separate themselves from adjoining elements. 
However, sometimes you will find that you need to increase (or decrease) the 
standard margins. 

For example, when using images, you may find the margin between the image and the 
surrounding elements too slim. An image next to text is shown in Figure 20-4. Notice 
that the "T" is all but touching the image. 

Note that the following code was used to separate the two elements: 

<img src="square . png" style="float: 1 ef t ; "><p>Text next to an image</p> 

You can use the margin properties to adjust the space around an element. There are 
properties to adjust each margin individually, as well as a shortcut property to 
adjust all the margins with one property. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



340 Part III ♦ Controlling Presentation with CSS 



@ Tight Margins - Microsoft Internet Explorer Q(n)S 



File Edit View Favorites Tools Help 

P iV * ® 



B B 



&■ 



Address 



http://localhost/Chapter20/Fig20-4.ritml 



: Go 






fext next to an image 



^JDone 



\j Local intranet 



Figure 20-4: The margins on some elements are 
too tight, as shown by how close the text is to the 
image. 



Tip 



The ma rgi n-top, ma rgi n- ri ght, margi n- bottom, and margin-left properties 
adjust the margins on individual sides of an element. The margin property can 
adjust one side or all sides of an element. The margin properties all have a simple 
format: 

margi n - ri ght : width; 
The ma rgi n shortcut property allows you to specify one, two, three, or four widths: 

margin: top right bottom left; 
For example, suppose you want to set the margins as follows: 

♦ Top: 2px 

♦ Right: 4px 

♦ Bottom: lOpx 

♦ Left:4px 

You could use this code: 

margin: 2px 4px lOpx 4px; 

You don't have to specify all four margins in the margi n property if some of 
the margins are to be set the same. If you only specify one value, it applies to 
all sides. If you specify two values, the first value is used for the top and bottom, 
and the second value is used for the right and left sides. If three values are given, 
the top is set to the first, the sides to the second, and the bottom to the third. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



Chapter 20 ♦ Padding, Margins, and Borders 341 



So let's return to the example in Figure 20-4, where the text is too close to the image. 
You can separate the two elements by increasing the right margin of the image, or 
the left margin of the text. However, you probably would not want to increase any of 
the other margins. 

T 'P There are no real guidelines when it comes to which margins to adjust on what 

\ elements. However, it's usually best to choose to modify the least number of 
margins or to be consistent with which margins you do change. 

Adding Padding within an Element 

Padding is the space between the element and its border. The configuration of the 
padding is similar to configuring margins — there are properties for the padding on 
each side of the element and a shortcut property for configuring several sides with 
one property. 

The properties for configuring padding are: paddi ng - top, paddi ng - ri ght, 
padding-left, paddi ng- bottom, and bottom. 

Note that you can use padding like a margin; increasing the padding increases the 
space between elements. However, you should use margins for increasing spacing 
between elements, and only use padding to help the legibility of the document by 
separating the element from its border. 

T 'P An element's background color extends to the edge of the element's padding. 

^v Therefore, increasing an element's padding can extend the background away 

' from an element. This is one reason to use padding instead of margins to 

increase space around an element. For more information on backgrounds, see 

Chapter 21. 



Adding Borders 



Unlike margins and padding, borders have many more attributes that can be 
configured using CSS. You can specify the look of the border, its color, its type, and 
various other properties. Each of the groups of properties is discussed in the 
following sections. 



Border style 



Note 



There are 10 different types of predefined border styles. These types are shown in 
Figure 20-5. 

The border type hi dden is identical to the border type none, except that the 
border type hidden is treated like a border for border conflict resolutions. Bor- 
der conflicts happen when adjacent elements share a common border (when 
there is no spacing between the elements). In most cases, the most eye-catching 
border is used. However, if either conflicting element has the conflicting border 
set to hi dden, the border between the elements is unconditionally hidden. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



342 Part III ♦ Controlling Presentation with CSS 



^P] Border Types - 


Microsoft Internet Explorer 








QES 


File Edit 


View F 


jvoiites Tools h 


elp 








# 


J 


• o ■ 


a 


55 


6 | P * « 


* 


- 


& m 4 






. i http://localt-ost/LhaFterZJ/hiczu-f:.htn-| 










UB« 


• 
• 
• 

1 






None &. Hidden 
Dotted 

Dashed 
















* 
* 
* 


Groove 










1 

a j 


Ridge 


















Solid 


I 




Tnset 






















Double 


j 






g)Don3 
















*j Local intranet 



Figure 20-5: The 10 different border types. 



The border-style properties include properties for each side (border- top- styl e, 
border- right-style, border- bottom-style, border- 1 eft- styl e) and a 
shortcut property for multiple sides (border- styl e). The individual side 
properties accept one border style value and sets the border on that side of the 
element to the type specified by that value. The following example sets all of the side 
borders of an element to dotted: 

border -styl e : dotted; 

The border- styl e shortcut property can set the border style for one or multiple 
sides of the element. Like most other shortcut properties covered in this chapter, 
values for this property follows these rules: 

♦ If you only specify one value, it applies to all sides. 

♦ If you specify two values, the first value is used for the top and bottom, while 
the second value is used for the right and left sides. 



♦ If three values are given, the top is set to the first, the sides to the second, and 
the bottom to the third value. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



Chapter 20 ♦ Padding, Margins, and Borders 343 



Border color 

The border color properties allow you to specify the color used for an element's 
borders. Like most other border properties, there are color properties for each side 
as well as a shortcut property that can affect multiple borders with one property. 

The border color properties are: border-top-col or, border- right- col or, 
border- bott om - col or, bottom -1 eft- col or, and border-col or. The 
individual side properties take a single color value, while the shortcut border-color 
takes up to four values. Like the border- sty 1 e property, how many values you 
enter determines what sides are affected by what values. (See the previous section 
for the rules used to apply multiple values.) 

The border color properties take color values in three different forms: 

♦ Color keywords — Black, white, maroon, and so on. See Appendix C for a list of 
color keywords. 

♦ Color hexadecimal values — This value is specified in the form: #r rggbb, where 
rr ggbb is two digits (in hexadecimal notation) for each of the colors red, 
green, and blue. See Appendix C for a list of color hexadecimal values. 

♦ Color decimal or percentage values — This value is specified using the rgb ( ) 
property. This property takes three values, one each for red, green, and blue. 
The value can be an integer between and 255 or a percentage. For example, 
the following specifies the color purple (all red and all blue, no green) in 
integer form: 

rgb(255, 0, 255) 

♦ And the following specifies the color purple in percentages: 

rgb(100%, 0, 100%) 



T 'P Most graphic editing programs supply RGB values in several different forms in 

their color palette dialog boxes. For example, take a look at the dialog box in 
Figure 20-6. 



, 



Note 



Border width 

The actual width of the border can be specified using the border width properties. 
As with the other border properties, there are individual properties for each side of 
the element, as well as a shortcut property. These properties are: border- top - 
width, border- right-width, border- bott om-width, border- left-width, 
and border-wi dth. 

The border-width shortcut property accepts one to four values. The way 
the values are mapped to the individual sides depends on the number of val- 
ues specified. The rules for this behavior are the same as those used for the 
border-style property. See the Border style section earlier in this chapter for 
the specific rules. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



44 Part III ♦ Controlling Presentation with CSS 



a 



■ 


1 


W 


_ 




■ 






■ 






■ 






iJ 








■ 




■■■ 


m 










■IB 










Add Custom 


1 














Hus: 

Sat 

Lignt: 

L code: 




Hed: [2bb 


dil 


|« 33 


Green: 1255 


=y 


|2 55 -y 






Bue: |Gi 

P' Link coors 




|iso -y 


JBFFFF40 




] 



J 



J 



Figure 20-6: Many graphic editing 
programs specify colors using multiple 
RGB value formulas that you can cut and 
paste into your Web documents. 



You can use the keywords t h i n, med i um, or t h i c k to roughly specify a border's 
width — the actual width used depends on the user agent. You can also specify an 
exact size using em, px, or other width/length values. For example, to set all the 
borders of an element to 2 pixels wide, you could use the following definition: 

border -wi dth : 2px; 



The ultimate shortcut: The border property 

You can use the border property to set the width, style, and color of an element's 
border. The border property has the following form: 

border: border-wi dth border- sty! e border- col or; 

For example, to set an element's border to thick, double, and red, you would use the 
following definition: 

border: thick double red; 



Additional border properties 

Two additional border properties are used primarily with tables: 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



Chapter 20 ♦ Padding, Margins, and Borders 34 



♦ border- spaci ng — This property controls how the user agent renders the 
space between the borders of the cells in a table. 

♦ border-col laps e — This property selects the "collapsed" model of table 
borders. 



Cross- These two border properties are covered in more depth with other table prop- 



Reference 



erties in Chapter 22. 



Using Dynamic Outlines 



Outlines provide another layer around the element to allow the user agent to 
highlight elements. For example, Figure 20-7 shows the default outline provided by 
Internet Explorer when a check box label is in focus. 



1 " Outlines - Microsoft Internet Explorer 



- H:K: 



File Edit View Fiivorites Tools Help 

O'O-a a el^ *• e|0' 



http://localhost/Chapter20/Fig20-8.html 



a 



How did you hear about our service? 
D friend 
D Magazine 

□ Television 

□ Other 



vl 



fi Done 



*J Local intranet 



Figure 20-7: The default outline provided by 
Internet Explorer— shown around the Friend label. 



Note 



Outlines are positioned directly outside the border of elements. The position 
of the outline cannot be moved directly, but can be influenced by the position 
of the border. Note that the outline does not occupy any space, and adding or 
suppressing outlines does not cause the content to be reflowed. 

Using CSS you can modify the look of these outlines. Unlike the other properties 
covered in this chapter, all sides of the elements outline must be the same; you 
cannot control the sides individually. 



P1:KTX 
WY022-20 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 8, 2004 15:21 



346 Part III ♦ Controlling Presentation with CSS 



The outline properties are outline-color, outline-style, outline-width, 
and the shorthand property outline. These properties work exactly like the other 
properties in this chapter, allowing the same values and having the same effects. 
Note that the format of the outl i ne shortcut property is as follows: 

outline: outline-color outline-style outline-width; 

To use the outline properties dynamically, use the : focus and : a cti ve pseudo- 
elements. These two pseudo-elements allow you to specify that an element's outline 
is visible only when the element has the focus or is active. For example, the following 
definitions specify a thick red border when form elements have focus and a thin 
green border when they are active: 



Note 



form *:focus { 
form *:active 



outline-width: thick; 
outl i ne-wi dth : thin; 



outline-color: 
outline-color: 



red ; 1 
green ; 



At the time of this writing, none of the popular Web browsers (Internet Explorer, 
Opera, Mozilla, and so on) handle outlines consistently or correctly. Some do 
not allow the outline to be modified, and some do not properly track focus or 
active elements. Therefore, when using outlines, it is best to extensively test 
your code on all platforms you will support. 



Summary 



The box formatting model and the elements that make up each HTML element's box 
is quite powerful. As you saw in this chapter, you can use the various, layered 
properties that make up the box in several ways within a document — from simple 
ornamentation purposes to advanced formatting. The next chapter covers colors 
and backgrounds, two additional pieces of the box model. 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Colors and 
Backgrounds 



The previous chapter introduced you to the CSS box 
formatting model and the concept of padding, borders, 
and margins. This chapter extends that discussion into colors 
and backgrounds, two additional components of the box 
formatting model. 



Foreground Color 

The foreground color of an element is the color that actually 
comprises the visible part of the element — in most cases, it is 
the color of the font. 

You can control the foreground color using the color 
property. This property has the following format: 

color: col or_val ue; 

The c o 1 o r_v a 1 u e can be specified in any of the usual means 
for specifying a color: 

♦ Color keywords — Black, white, maroon, and so on. 

♦ Color hexadecimal values — This value is specified in the form: 
#rrggbb, where rrggbb is two digits (in hexadecimal 
notation) for each of the colors red, green, and blue. 

♦ Color decimal or percentage values — This value is specified 
using the rgb ( ) property. This property takes three values, 
one each for red, green, and blue. The value can be an integer 
between and 255 or a percentage. For example, the following 
specifies the color purple (all red and all blue, no green) in 
integer form: 

rgb(255, 0, 255) 

♦ And the following specifies the color purple in percentages: 

rgb(100%, 0, 100%) 



C H 



T E 



♦ ♦ ♦ ♦ 

In This Chapter 

Foreground Color 

Background Color 

Sizing an Element's 
Background 

Background Images 

Repeating and Scrolling 
Background Images 

Positioning Background 
Images 



347 



P1:KTX 

WY022-21 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



48 Part III ♦ Controlling Presentation with CSS 



T 'P Most graphic editing programs supply RGB values in several different forms in 

their color palette dialog boxes. 

For example, to set the font color to red for paragraph elements in the redtext 
class, you could use this definition: 

p . redtext { color: red ; I 

When specifying foreground colors, keep in mind what background colors will be 
used in the document. It's ineffective to use red text on a red background, or white 
text on a white background, for example. If you have multiple background colors in 
your document, consider using classes and the CSS cascade to ensure that the right 
foreground colors are used. 

Keep in mind that the user settings can affect the color of text as well — if you don't 
explicitly define the foreground color, the user agent will use its default colors. 



Background Color 



The background color of an element is the color of the virtual page that the element 
is rendered upon. For example, Figure 21-1 shows two paragraphs — the first has a 
default white background, and the second has a light gray background. 

Note Saying that the document has a default color of white is incorrect. Technically, 

the document will have the color specified in the rendering user agent's settings. 
In typical Internet Explorer installations (as shown in Figure 21-1), the color is 
indeed white. 

To specify a background color, you use the background-col or property. This 
property has a format similar to other color setting properties: 

background -col or : col or_vdl ue; 

For example, to set the background of a particular paragraph to blue, you could use 
the following definition: 

<p styl e="background -col or : blue; color: white">This 
paragraph will render as white text on a blue background. </p> 

Note that the definition also sets the color property so the text can be seen on the 
darker background. The result is shown in Figure 21-2. 



Sizing an Element's Background 



An element's background is rendered within the element's padding space — that is, 
inside the border of the element. For a visual example, take a look at Figure 21-3. 
Each paragraph specifies a slightly larger padding value (thick borders have been 
added to each paragraph for clarity). 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 21 ♦ Colors and Backgrounds 349 



@ Background Colors - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



o-a-aHiftp&#e &* & m & 



,: . http://localhost/Chapter21/Fig21-l.html 



Qgo 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibti 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex ea 
commodo consequat. Duis autern vel eurn iriure dolor in hendrerit in vulputate velit esse 
molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et accumsan et 
msto odio dignissim qui blandit praesent luptatum zznl delenit augue duis dolore te feugait 
nulla facilisi. 

Ut wisi eram ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi 
ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in 
vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero 
eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing 
elit, sed diam nonummy nibli euismod tincidunt ut laoreet dolore magna aliquam erat 
volutpat. 



v| 



*_J Local intranet 



Figure 21-1 : Background colors can be used to affect the color of the virtual 
page elements are rendered on. 



Background Images 



Besides using solid colors for backgrounds you can also use images. For example, 
the paragraph in Figure 21-4 uses a gradient image for the first paragraph (the image 
is shown by itself after the paragraph for comparison). 

To add an image as a background, you use the background-image property. This 
property has the following format: 

background -image: url ( " url _to_image") ; 

For example, the paragraph in Figure 21-4 uses the following code, which specifies 

g r a d i e n t . g i f as the background image: 



p 1 background- image: url("gradient.gif"); 
height: lOOpx; width: 500px; 
border: thin solid black; 1 



P1:KTX 

WY022-21 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



350 Part III ♦ Controlling Presentation with CSS 



@ Background and Foreground Colors - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 



> : 



Q'<D-HE*fciP£tf 



* fit SI 41 



Address :g] http://localhost/Chapter21/Fig21-2.hrrnl 



H 



Lor 
euis 
vein 

COn 


sin lpsurn dolor sit amet, consectetuer ad 
mod tincidunt ut laoreet dolore magna all 
am, quis nostrud exerci tation ullamcorpe 
imodo consequat. Duis autem vel eum irii 


piscing elit, sed diam nonui 
quam erat volutpat. Ut wisi 
r suscipit lobortis nisi ut alit 
are dolor in hendrerit in vul] 


limy nibh 
enim ad mini 
juip ex ea 
jutate velit es 
et accumsan 


m 

se 
et 


mol 


sstie consequat, vel ilium dolore eu feugia 


t nulla facilisis at vero eros 


(USfe 

null; 


> odio digrussim qui blandit praesent lupts 
i facilisi. 


turn zzril delenit augue duis 


dolore te fei 


gait 



*_J Local intranet 



Figure 21-2: When using a dark background color, you should usually use a 
light foreground color. 



Note 



The example shown in Figure 21-4 has a few additional properties defined to 
help make the example. A border was added to the paragraph and image to 
help show the edges of the image. The height and width of the paragraph were 
constrained to the size of the image to prevent the image from repeating. For 
more on repeating and scrolling background images, see the next section. 



The background image can be used for some interesting effects, as shown in 
Figure 21-5, where a frame image is used as text ornamentation. (Again, the image is 
repeated alone, with border, for clarification of what the image is.) 

The following CSS definition is used for the paragraph in Figure 21-5: 

p.catborder { height: 135px; width: 336px; 
background- image: url ("cat. g if") ; 
padding: 80px 135px 18px 18px; ) 

This code uses several additional properties to position the text within the border 
frame: 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 21 ♦ Colors and Backgrounds 351 



@ Background Sizing - Microsoft Internet Explorer 



BBS 



File Edit View Favorites Tools Help 

GO B E & I P * • © 



0- ^ ■ $ 



Address 



|http://localhost/Chapter21/Fig21-3.html 






Standard padding: Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi 
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut 
aliquip ex ea commodo consequat. 



5px padding: Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut 
wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi 
ut aliquip ex ea commodo consequat. 



lQpx padding: Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut 
wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis 
nisi ut aliquip ex ea commodo consequat. 



ISpx padding: Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam 
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut 
wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis 
nisi ut aliquip ex ea commodo consequat. 



*J Local intranet 



Figure 21-3: An element's background extends to the edge of its 
padding— sizing the padding can size the background. 



♦ Explicit width and height properties specify the size of the full image. 
4- Explicit paddi ng values ensure that the text stays within the box. 



Repeating and Scrolling Background Images 

Element background images act similarly to document background images — by 
default, they tile to fill the given space. For example, consider the paragraph in 
Figure 21-6, where the smiley image is tiled to fill the entire paragraph box. 

Notice, also, how the right and bottom of the background are filled with incomplete 
copies of the image because the paragraph size is not an even multiple of the 
background graphic size. 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



352 Part III ♦ Controlling Presentation with CSS 



fi Background Images - Microsoft Internet Explorer 



- -, x 



File Edit View Favorites Tools Hel|> 



o - ■, 

Address 



P * * & 



m % 



http : //localhost/Chapter2 1 /Fig2 1 -4 . html 



I! 

a go 



Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat Ut wisi enim ad 
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip 
ex ea commodo consequat. 



§}Da 



*j Local intranet 



Figure 21-4: You can also use images for element backgrounds. 



You can specify the repeating nature and the actual position of the background 
image using the background- repeat and background-attachment properties. 
The background-repeat property has the following format: 

background - repeat : repeat \ repedt-x \ repeat-y \ no- repeat; 

The background-attachment property has the following format: 

background -attachment : scroll \ fixed; 

The background -repeat property is straightforward — its values specify how the 
image repeats. For example, to repeat our smiley face across the top of the paragraph, 
specify repeat- x, as shown in the following definition code and Figure 2 1-7: 

p. smiley I background -image : url ( "smi 1 ey . gi f " ) ; 
background - repeat : repeat-x; 
/* Border for clarity only */ 
border: thin solid black; I 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 21 ♦ Colors and Backgrounds 353 



r- " Advanced E:.rn:k(|nniinl 1 1 1 1 :n j e s - Miaosoft Internet Ex|>l<nei 



- -l K- 



Help 



File Edit View Favorites Tools 

q & s m >$> . p t? # • 



* 



m $ 



Address 



| http : y/localhostychapter2 1 /FigZ 1 -5 . html 



BET 




Lorem ipsum dolor sit amet, consectetuer adipiscing 
elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi 
enim ad minim veniam, quis nostrud exerci tation 
ullamcoiper suscipit lobortis nisi ut aliquip ex ea 
comrnodo consequat. 





\J Local intranet 



Figure 21-5: Background images can be used as textual ornamentation. 



The background-attachment property controls how the background is attached 
to the element. The default value, s c rol 1 , allows the background to scroll as the 
element is scrolled. The fixed value doesn't allow the background to scroll; instead, 
the contents of the element scroll over the background. 

The scroll behavior can be seen in Figure 21-8 where two identical elements are 
shown. The bottom paragraph has been scrolled a bit, and the background scrolls 
with the element's content. 



The following code is used for the paragraphs in Figure 21-8: 

p . smi 1 eyscrol 1 { height: 220px; width: 520px; 
overflow: scroll; 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



354 Part III ♦ Controlling Presentation with CSS 



{Tiled Background Images - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 

• a m <& i ? «jr @ a* I* is ■$ 

Address 



http://localho5t/Chapter21/Fig21-6,html 



Lorera ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim 
sreniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex ea 
commodo consequat. Duis autem vel eum inure dolor in hendrerit in vulputate velit 
esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accurnsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis 
dolore te feugait nulla facilisi. 



^5r ^8f ^Bf ^Bf ^Bf ^Bf ^Bf ^Bf ^Bf ^Sf ' 



# 



H 



iS)Done 



*j Local intranet 



Figure 21-6: By default, background images will tile to fill the available space. 



Note 



background- image: url ("smiley.gif") ; 
background -attachment : scroll; 
border: thin solid black; 1 

Notice the use of the overflow property in the code for Figure 21-8. This prop- 
erty controls what happens when an element's content is larger than the ele- 
ment's defined box. The scrol 1 value enables scroll bars on the element so 
the user can scroll to see the rest of the content. The overflow property also 
supports the values visible (which causes the element to be displayed in its 
entirety, despite box size constraints) and hidden (which causes the part of 
the element that overflows to be clipped and inaccessible). 



If you change the background-attachment value to fixed, the background image 
remains stationary, as shown in Figure 21-9. 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 21 ♦ Colors and Backgrounds 355 



^j Tiled X Background Images - Microsoft Internet Explorer 



B(g)B 



File Edit View Favorites Tools Help 



it 



Q-Q-\Eim<&\Pis#e> 0-&P-$ 



„ http://localho5t/Chapter21/Fig21-7.html 



r]B Go 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonurnmy rabh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex ea 
commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit 
esse rnolestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et msto odio dignissim qui blandit praesent luptatum zznl delenit augue duis 
dolore te feugait nulla facilisi. 



* j Local intranet 



Figure 21-7: Repeating a background image horizontally with the repeatx value of the 

background-repeat property 



T 'P Non-scrolling backgrounds make great watermarks. Watermarks— named for 

"^ the process of creating them on paper— are slight images placed in the back- 
' ground of documents to distinguish them. Some companies place watermarks 
of their logo on their letterhead. 



Positioning Background Images 



The background -positi on property allows you to position an element's 
background image. This property's use isn't as straightforward as some of the other 
properties. The basic forms of the values for this property fall into three categories: 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



356 Part III ♦ Controlling Presentation with CSS 



♦ Two percentages that specify where the upper-left corner of the image should 
be placed in relation to the element's padding area 

♦ Two lengths (in inches, centimeters, pixels, em, and so on) that specify where 
the upper-left corner of the image should be placed in relation to the element's 
padding area 

4- Keywords that specify absolute measures of the element's padding area 

No matter what format you use for the background-position values, the format is as 
follows: 



background -posi ti on : hori zontal _val ue verti cal _val ue; 



jjsj Scrolling Background Images - Microsoft Internet Explorer 



- -i ; R; 



File Edit View Favorites Tools Help 

o - a a id & ' p * « « 



®~ & ■ .$ 



: .:. , http://localhost/Chapter21/Fig21-8.ritml 



BB' 



Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed diam nonummy nibh 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad 
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip 
ex ea commodo consequat. Duis autern vel eum inure dolor in hendrent in vulputate 
ffelit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et lusto odio dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit arnet, consectetuer 
adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna 
aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea cornrnodo consequat. Duis autem 



<rpl pntri irii lrp 



1-1^1^: 



i hpn^lrpnt in TniltMit-atp irplit - ps^p triAlp^tip r-An^pfinat vpl illnt^ 



ffelit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et lusto odio dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit arnet, consectetuer 
adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna 
aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea cornrnodo consequat. Duis autem 
vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium 
dolore eu feugiat nulla facilisis at vero eros et accumsan et lusto odio dignissim qui 
blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. 
Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed diam nonummy nibh 

™.-.,] fc»»;j,»i,*U™»t jJaWp ™X™U iU'/ii^w «~>*-..Al,rt^™t TH-™'™ p.,™ ^A 



*j Local intranet 



Figure 21-8: Backgrounds scroll by default, as shown by the second paragraph. 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 21 ♦ Colors and Backgrounds 357 



ig] Fixed Background Images - Mkiosoft Internet Explorer 



- -i £) 



File Edit View Favorites Tools Help 

O • O • B «i P**# 



,'! 



a- Si m & 



Address 



http : //localhost/Chapter2 1 /Fig2 1 -9 . html 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh I 
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enirn ad 
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip 
ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate 
velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et lusto odio dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer 
adipiscing elit, sed diani nonummy rubh euismod tincidunt ut laoreet dolore magna 
aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem 

vpl piim innrp dolor m hpfldrpnt in imlnntfltp vplit p^p molp^tip rnn^pnnat vpl i11nm I 






ta rd Luimnuuu Luntrquiii. uuis duinn m cuiuuiuir uuiui iuiiciiuiciuiii vuipuuic | 
velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et lusto odio dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer 
adipiscing elit, sed diani nonummy nibh euismod tincidunt ut laoreet dolore magna 
aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nislut aliquip ex ea commodo consequat. Duis autem 
vel eum inure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium — 
dolore eu feugiat nulla facilisis at vero eros et accumsan et lusto odio dignissim qui 
blandit praesent luptatum zznl delenit augue duis dolore te feugait nulla facilisi. 
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh f v 






*j Local intranet 



Figure 21-9: You can specify that a background image remain fixed under the element 
with the background-attachment property. 

If only one value is given, it is used for the horizontal placement — the image is 
centered vertically. You can mix the first two formats (for example, lOpx 25%), but 
keywords cannot be mixed with other values (for example, center 50% is invalid). 

The first two forms are much like the value formats used in other properties. For 
example, the following definition positions the upper-left corner of the background 
in the middle of the element's padding area: 

background-position: 50% 50%; 

The next definition places the upper-left corner of the background 25 pixels from the 
top and left sides of the element's padding area: 



background -posi ti on : 25px 25px; 



P1:KTX 
WY022-21 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



358 Part III ♦ Controlling Presentation with CSS 



Several keywords can be used for the third format of the background -position 
property. They include top, 1 eft, right, bottom, and center. 

For example, you can position the background image in the top, center of the 
element's padding using the following: 

background-position: top center; 

Or, you can position the background image directly in the center of the element's 
padding with the following: 



background-position: center center; 

T 'P Combining the background attributes can achieve more diverse effects. For 

example, you can use background -position to set an image in the center 
of the element's padding, and specify background -attachment: fixed to 
keep it there. Furthermore, you could use background- repeat to repeat 
the same image horizontally or vertically, creating dynamic striping behind the 
element. 



/ 



Summary 



This chapter completes the concept of a box formatting model and how it is used 
and manipulated by CSS. You learned about foreground colors, background colors, 
and background images. You learned how these components can be manipulated 
separately or combined for maximum formatting effect. The next chapter covers 
another powerful formatting tool — tables. Chapter 23 rounds out the CSS element 
formatting subject by showing you how to position elements using CSS. 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



Tables 



Earlier in this book, you learned how to use tables to 
format documents. This chapter explains how CSS can 
make a great formatting tool even better. Although many table 
tag attributes still exist in the strict HTML standards, CSS 
offers many advantages when formatting tables. 



Defining Table Styles 



Because the <ta bl e> tag attributes, such as border, rules, 
cellpadding, and cellspacing, have not been deprecated, you 
might be tempted to use them instead of styles when defining 
your tables. Resist that temptation. 

Using styles for tables has the same advantages as using styles 
for any other elements — consistency, flexibility, and the ability 
to easily change the format later. 

For example, consider the following table tag: 



♦ ♦ ♦ ♦ 
In This Chapter 

Defining Table Styles 

Controlling Table Attributes 

Table Layout 

Aligning and Positioning 
Captions 



<table border="l" width="2C 
eel 1 spaci ng="5px"> 



)px" eel 1 paddi ng="3px' : 



Now suppose you had four tables using this definition in your 
document, and you had four documents just like it. What if you 
decided to decrease the width and increase the padding in the 
tables? You would have to edit each table, potentially 16 
individual tables. 

If the table formatting were contained in styles at the top of the 
documents, you would have to make four changes. Better yet, 
if the formatting were contained in a separate, external style 
sheet, you would only have to make one change. 

The border properties can be used to control table borders, 
and the padding and margin properties can affect the spacing 
of cells and their contents. 




359 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



360 Part III ♦ Controlling Presentation with CSS 



Controlling Table Attributes 

You can use CSS properties to control the formatting of tables. One issue with using 
CSS is that some of the properties do not match up name-wise with the tag attributes. 
For example, there are no eel 1 spaci ng or eel 1 paddi ng CSS properties. The 
border- spacing and paddi ng CSS properties fill those roles, respectively. 

Table 22-1 shows how CSS properties match table tag attributes. 



CSS 


Table 22-1 
Properties for Table 


Attributes 


Purpose 


Table Attribute 


CSS Property(ies) 


Borders 


border 


border properties 


Spacing inside cell 


eel 1 padding 


padding 


Spacing between cells 


eel 1 spaci ng 


border-spaci ng 


Width of table 


width 


width and table-layout 
properties 


Table framing 


frame 


border properties 


Alignment 


al ign, val ign 


text- al ign, verti cal - 
alignment properties 



Table borders 

You can use the border properties to control the border of a table and its 
subelements just like any other element. For example, the following definition 
causes all tables and their elements to have single, solid, lpt borders around them 
(as shown in Figure 22-1): 

table, table * { border: lpt solid black; 1 

Note that we specified all tables and all table descendents (table, table *) to 
ensure that each cell, as well as the entire table, has a border. If you wanted only the 
cells or only the table to have borders, you could use the following definitions: 

/* Only table cells have borders */ 
table * 1 border: lpt solid black; 1 



/* Only table body has borders */ 
table ( border: lpt solid black; 1 



The results of these two definitions are shown in Figure 22-2. 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



Chapter 22 ♦ Tables 361 



It) CSS Tables - Mozilla Firebird 



- -i(2 



File Edit View Go Bookmarks Tools Help 



I "*& k t& | h1tp://localhos1,|v| [Q~ 



Employee 


Start Dare Next Review 


Branden R. 


2/15/00 


2/28/04 


Theresa M. 


11/15/03 


3/31/04 


TamaraD. 


8/25/02 


2/28/04 


Steve H. 


11/02/00 


3/31/04 


IanM. 


4/2/99 


n/a 



Done 



Figure 22-1: A table using CSS formatting. 



H£) CSS Tables - Mozilla Firebird 



BOB 



File Edit View Go Bookmarks Tools Hel 



-®'«i*©is: 



Cells borders only 



Employee 


Start Date 


Next Review 


Branden R. 


2/15/00 


2/28/04 


Theresa M. 


11/15/03 


3/31/04 


TamaraD. 


8/25/02 


2/28/04 


Steve H. 


1 1/02/00 


3/31/04 


IanM. 


4/2/99 


n/a 



Table body borders only 



Employee 


Start Date Next Review 


Branden R. 


2/15/00 


2/28/04 


Theresa M 


11/15/03 


3/31/04 


TamaraD. 


8/25/02 


2/28/04 


Steve H. 


11/02/00 


3/31/04 


IanM. 


4/2/99 


n/a 



Done 



Figure 22-2: A table using selective 
bordering. 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



362 Part III ♦ Controlling Presentation with CSS 



You can also combine border styles. For example, the following definitions create a 
table with borders similar to using the border attribute. The result of this definition 
is shown in Figure 22-3. 

table { border: outset 5pt; ) 
td { border: inset 5pt; I 



It} Border Spacing - Mozilla Firebird 



- 5]S 



File Edit View Go Bookmarks Tools He 



"*-* :>t5>i§r 



Employee 



Start Date Next Review 



¥ 



randen R. 



lib 



eresaM. 



f 



amaraD. 



ISteve H. 



F 



ianM. 



2/15/00 



11/15/03 



i/25/02 



11/02/00 



4/2/99 n/a 



2/28/04 



3/31/04 



2/28/04 



3/31/04 



Done 



Figure 22-3: You can combine border styles 
to create custom table formats. 



Table border spacing 



Note 



To increase the space around table borders, you use the border -spaci ng and 
paddi ng CSS properties. The border -spacing property adjusts the space between 
table cells much like the <tabl e> tag's cellspacing attribute. The paddi ng 
property adjusts the space between a table cell's contents and the cell's border. 

The border -spacing property has the following format: 

border-spacing: horizontals pacing vert ical_s pacing; 

Note that you can choose to include only one value, in which case the spacing is 
applied to both the horizontal and vertical border spacing. 

For example, Figure 22-4 shows the same table as in Figure 22-1, but with the 
following border-spacing definition: 

border-spacing: 5px 15px; 

Some user agents, such as Internet Explorer, disregard the border-spacing 
property. See Appendix B for a full list of what browsers support what properties. 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



Chapter 22 ♦ Tables 363 



{© Bonier Spacing - Mozilla Firebird B[gB 



File Edit View Go Bookmarks Tools Hel 



®^-t£ .»t>l 





Employee 


|startDaie 


iNeir Review 




Branden R. 


|2/15/00 


|2/28/04 




[Theresa M. 


11/15/03 


3/31/04 




fTamaraD. 


|8/25/02 


|2/28/04 




Steve H. 


|l 1/02/00 


|3/31/04 




IanM. 


\\nm 


|n/a 





Done 



Figure 22-4: Different horizontal and vertical 
border-spacing can help distinguish data 
in columns or rows. 



Collapsing borders 

Sometimes you will want to remove the spacing between borders in a table, creating 
gridlines instead of cell borders. To do so, you use the border -col 1 apse property. 
This property takes either the value of separate (default) or c o 1 1 a p s e . If you 
specify collapse, the cells merge their borders with neighboring cells (or the table) 
into one line. Whichever cell has the most visually distinctive border determines the 
collapsed border's look. 

For example, consider the two tables in Figure 22-5, shown with their table 
definitions directly above them. 

Notice how the borders between the table headers and normal cells inherited the 
inset border while the rest of the borders remained solid. This is because the border 
around the table headers was more visually distinctive and won the conflict between 
the borders styles being collapsed. 



Borders on empty cells 



Typically, the user agent does not render empty cells. However, you can use the 
empty -cells CSS property to control whether the agent should or should not show 
empty cells. The empty-eel 1 s property takes one of two values: show or hi de 
(default). 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



64 Part III ♦ Controlling Presentation with CSS 



j£) Border Collapse Mozilla Firebird 



File Edit View Go Bookmarks Tools Help 



#-&-^ ^ fffc | ht1p:;/lccalhost/Cia3ter[^] [C^~ 



tcJolc,- 3oblc td ( border : ODlici £pt black; 
LtJule L:i { Ijujidei: inteL 3pL; > 



1 Einpluyee 1 Slaii Dale 1 Neil Review 


(BrandsnR. ||2/15/30 ||2/2S/04 


flhe-esaM || 1/15/03 ||3/3 J/04 


llamaraJJ. ||K/23/J2 ||2i2t;/04 


|SteveH. ||: 1/02/00 ||3/3 1/04 


fan M ||4/2/99 ||n/a 



table. 3 able td ( bortier: SDlici 2pt black; 

bor tier-col lapse : CDllapse; i 
table t!.i { border: inset 3pt; } 



- n(3 



Employee 


Start Date 


Next Review 


Branded R. 


2' 15/00 


2/28'04 


Theresa M. 


11/1 5'03 


3/31/04 


Tamars E. 


8/25/02 


2/28/04 


Steve H. 


ll/02.'O0 


3/31/04 


IsnM 


4'2/95 


ti/a 



Figure 22-5: Collapsing table borders turns individual 
borders into gridlines between cells. 

Figure 22-6 shows the following table with various settings of the empty -cells 
property. 



Note 



(table) 

<tr><th>Heading</thXth>Heading</th><th>Heading</thX/tr> 

<tr><td>X</td><td></td><td>X</tdX/tr> 

<trXtdX/tdXtd>X</tdXtdX/tdX/tr> 

<trXtd>X</tdXtd>X</tdXtd>X</tdX/tr> 
(/table> 

Some user agents, such as Internet Explorer, disregard the empty -eel 1 s prop- 
erty. See Appendix B for a full list of what browsers support what properties. 



Table Layout 



The tabl e - 1 ayout property determines how a user agent sizes a table. This 
property takes one of two values, auto or fixed. If this property is set to auto, the 
user agent automatically determines the table's width primarily from the contents of 
the table's cells. If this property is set to fixed, the user agent determines the table's 
width primarily from the width values defined in the tags and styles. 



P1:KTX 

WY022-22 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



^5 Border Collapse - Mozilla Firebird 



File Edit View Go Bookmarks Tools Help 



® ' *J ' *& . t& | http://localhost/Chapterp1 [C^~ 



empty- cells not specified 



Heading 



Heading 



Heading 



]E 



empty- cells: show; 



Heading 



Heading 



Heading 



K 



]E 



empty- cells: hide; 



1 Heading | Heading J Heading 


X X 


Ix 


x |x X 



Done 



Chapter 22 ♦ Tables 365 



- n© 



^ 



Figure 22-6: The empty eel 1 s property controls whether the 
user agent displays empty cells or not. 



Aligning and Positioning Captions 

CSS can also help control the positioning of table caption elements. The positioning 
of the caption is controlled by the capt ion-side property. This property has the 
following format: 

capti on -si de : top | bottom | left | right; 

The value of the property determines where the caption is positioned in relationship 
to the table. To align the caption in its position, you can use typical text alignment 
properties such as text-al i gn and verti cal -al i gn. 

For example, the following code places the table's caption to the right of the table, 
centered vertically and horizontally, as shown in Figure 22-7. 



1D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 01// Eh 

"http://www.w3.org/TR/html4/strict.dtd"> 



P1:KTX 

WY022-22 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



66 Part III ♦ Controlling Presentation with CSS 



<html> 
(head) 

<title>Table Caption Positioning</title> 
<style type="text/css"> 

table { margi n - ri ght : 200px; ) 

table, table * I border: lpt solid black; 

caption-side: right; 1 
caption { margi n - 1 eft : lOpx; 

vertical -align: middle; 
text -align: center ; 1 
</style> 
</head> 
<body> 
<p> 
(table) 

<tr><th>Employee</thXth>Start Date</th> 

<th>Next Review</thX/tr> 
<tr><td>Branden R. </td><td>2/ 15/00</td> 

<td>2/28/04</td></tr> 
<trXtd>Theresa M X/tdXtd>ll/15/03</td> 

<td>3/31/04</td></tr> 
<tr><td>Tamara D . </td><td>8/25/02</td> 

<td>2/28/04</tdX/tr> 
<tr><td>Steve H . </td><td>ll/02/00</td> 

<td>3/31/04</tdX/tr> 
<trXtd>Ian M . </td><td>4/2/99</td> 

<td>n/a</tdX/tr> 
<capti on>Tech Employee Review Schedul e</capt i on) 
</table> 
(/p> 
(/body) 
</html> 



i£)Ta hle Caption Positioning - Mozilla Firebird 



- b O 



File Edit View Go Bookmarks Tools Help 



<* 



>' T ^ .■> fe I http://localhos1/Chi|y1 [OT 



Employee 


Start Date 


Next Review 


Branden R. 


2/15/00 


2/28/04 


Theresa M. 


11/15/03 


3/31/04 


TarnaraD. 


S/25/02 


2/28/04 


Steve H. 


11/02/00 


3/31/04 


IanM. 


412199 


n/a 



Tech Employee Review 
Schedule 



Done 



Figure 22-7: Positioning a caption to the right of a table. 



P1:KTX 
WY022-22 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



Chapter 22 ♦ Tables 367 



Note that the table's caption is positioned inside the table's margin. By increasing 
the margin of the table, you allow more text per line of the caption. You can also 
explicitly set the width of the caption using the width property, which increases the 
margins of the table accordingly 



Summary 



As you saw in this chapter, combining tables and CSS makes for a great, dynamic 
formatting tool for Web documents. 



P1:KTX 

WY022-22 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 9, 2004 15:0 



368 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Element 
Positioning 



In the various chapters within this section, you have seen 
how dynamic documents can be when formatted with CSS. 
This chapter shows you how you can position elements using 
CSS properties. 



Understanding Element 
Positioning 

There are several ways to position elements using CSS. The 
method you use depends on what you want the position of the 
element to be in reference to and how you want the element to 
affect other elements around it. The following sections cover 
the three main positioning models. 

Static positioning 

Static positioning is the normal positioning model — elements 
are rendered inline or within their respective blocks. 
Figure 23-1 shows three paragraphs; the middle paragraph 
has the following styles applied to it: 

width: 350px; height: 150px; 
border: Ipt solid black; 
background -col or : white; 
padding: .5em; 
position: static; 



Note 



Several styles have been inserted for consistency 
throughout the examples in this section. A border and 
background have been added to the element to enhance 
the visibility of the element's scope and position. The el- 
ement also has two positioning properties (top and left), 
although they do not affect the static positioning model. 



Understanding Element 
Positioning 




Specifying Element Position 

Floating Elements to the Left 
or Right 

Defining an Element's 
Width and Height 

Stacking Elements in Layers 

Controlling Element 
Visibility 



369 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



370 Part III ♦ Controlling Presentation with CSS 



!f'l Div Positi oning - Mozilla Firebird 



- "i E 



File Edit View Go Bookmarks Tools Help 



® " "*' " \& * fe | http://localhost/Chapter23/Fig23-1 .htmT 



K 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt 
ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci 
tation ullamcorper suscipit lobortis nisi ut aliquip ex ea comrnodo consequat. Duis autem vel eum 
inure dolor in hendrent in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla 
facilisis at vero eros et accumsan et msto odio dignissim qui blandit praesent luptatum zzril delenit 
augue duis dolore te feugait nulla facilisi. 



Ut wisi enim ad minim veniam, quis nostrud eserci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea commodo 
consequat. Duis autem vel eum inure dolor in hendrent in 
vulputate velit esse molestie consequat, vel ilium dolore eu 
feugiat nulla facilisis at vero eros et accumsan et lusto odio 
dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. 



Duis autem vel eum inure dolor in hendrent in vulputate velit esse molestie consequat, vel ilium dolore 
eu feugiat nulla facilisis at vero eros et accumsan et lusto odio dignissim qui blandit praesent luptatum 
zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer 
adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat 
volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut 
aliquip ex ea commodo consequat. 



Done 



Figure 23-1: Static positioning is the normal positioning model, rendering elements 
where they should naturally be. 



Relative positioning 



Relative positioning is used to move an element from its normal position — where it 
would normally be rendered — to a new position. The new position is relative to the 
normal position of the element. 



Figure 23-2 shows the second paragraph positioned using the relative positional 
model. The paragraph is positioned using the following styles (pay particular 
attention to the last two, position and top): 

width: 350px; height: 150px; 
border: Ipt solid black; 
background-color: white; 
padding: .5 em; 
position: relative; 
top: lOOpx; left: lOOpx; 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 371 



jtt Div Positioning -Mozilla Firebird 



- n.S 



File Edit View Go Bookmarks Tools Help 



® T * T *& ,-i f»t | http://lccalhost/Cha[]ter23/Fig23-2.htrnT 



HEZ 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt 
ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrad exerci 
tation ullamcorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel eum 
inure dolor in hendrent in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla 
facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit 
augue duis dolore te feugait nulla facilisi. 



Duis autem vel e 
eu feugiat nulla fi 
zzril delenit augu 



Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea commodo 
consequat. Duis autem vel eum inure dolor in hendrent in 
vulputate velit esse molestie consequat, vel ilium dolore eu 



feugiat nulla facilisis at vero eros et accumsan et iusto odio idit praesent luptatum 



dignissim qui blandit praesent luptatum zzril delenit augue 



adipiscing elit, se duis dolore te feugait nulla facilisi. 



iequat, vel ilium dolore 



:t, consectetuer 
pa aliquam erat 



volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut 
aliquip ex ea commodo consequat. 



Done 



H 



Figure 23-2: Relative positioned elements are positioned relative to the position they 
would otherwise occupy. 



Note 



With relative positioning, you can use the side positioning properties (top, 1 eft, 
and so on) to position the element. Note the one major side effect of using relative 
positioning — the space where the element would normally be positioned is left open, 
as though the element were positioned there. 

The size of the element is determined by the sizing properties (width or 
hei ght), the positioning of the element's corners (via top, 1 eft, and so on), 
or by a combination of properties. 



Absolute positioning 



Elements using absolute positioning are positioned relative to the view port instead 
of their normal position in the document. For example, the following styles are used 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



372 Part III ♦ Controlling Presentation with CSS 



to position the second paragraph in Figure 23-3: 

width: 350px; height: 150px; 
border: Ipt solid black; 
background-color: white; 
padding: .5 em; 
position: absolute; 
top: lOOpx; left: lOOpx; 



) Div Positioning - Mozilla Firebird 



- n'© 



File Edit View Go Bookmarks Tools Help 



^ 



' "*■' "^ t %$ | http://localhcst/Ch af]ter23/Fig23-3.html 



K 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea cornrnodo consequat. Duis autem vel eum inure dolor in 
hendrent in vi |at nulla facilisis at vero eros 

et accumsan i TT ..... . , .t augue duis dolore te feugait 

I IfTBTici ptiim a/1 tnimrri upmam nine tinetnifl pvpfn fatirtti 

nulla facilisi. 



Duis autem vi 
feugiat nulla £ 
delenit augue 
sed diam non 
ad minim ven , 
consequat. 



Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea cornrnodo 
consequat. Duis autem vel eum inure dolor in hendrent in 
vulputate velit esse molestie consequat, vel ilium dolore eu 
feugiat nulla facilisis at vero eros et accumsan et msto odio 
dignissim qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. 



onsequat, vel ilium dolore eu 
tidit praesent luptatum zzril 
, consectetuer adipiscing elit, 
erat volutpat. Ut wisi enim 
1 ut aliquip ex ea cornrnodo 



Done 



Figure 23-3: The absolute positioning model uses the user agent's view port for 
positioning reference. 

Note that the positioning properties are referenced against the view port when using 
the absolute positioning model — the element in this example is positioned lOOpx 
from the top and lOOpx from the left of the view port edges. 



Unlike the relative positioning model, absolute positioning does not leave space 
where the element would have otherwise been positioned. Neighboring elements 
position themselves as though the element were not present in the rendering 
stream. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 373 



Fixed positioning 



Fixed positioning is similar to relative positioning in that the element is positioned 
relative to the view port. However, fixed positioning causes the element to be fixed in 
the view port — it will not scroll when the document is scrolled; it maintains its 
position. The following code is used to position the second paragraph shown in 
Figures 23-4 and 23-5. 

width: 350px; height: 150px; 

border: Ipt solid black; 

background -col or : white; 

padding: .5em; 

position: fixed; 

top: lOOpx; left: lOOpx; 

Note that when the document scrolls (Figure 23-5) the fixed element stays put. 



Itt Diu Positioning - Mozilla Firebird 



- 10 



File Edit View Go Bookmarks Tools Help 



^ 



T f , T ^ 



hn , p://localhost/Chapter23/Fig23-4.html 



<.. 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt 
ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci 
tation ullamcorper suscipit lobortis nisi ut aliquip ex ea cornmodo consequat. Duis autem vel eum 
inure dolor in ~ 
facilisis at ver 



augue duis dc 



Ut wisi enim ad minim veniam, quis nostrud exerci tation 

ullamcorper suscipit lobortis nisi ut aliquip ex ea cornmodo 

consequat. Duis autem vel eum inure dolor in hendrent in 

vulputate velit esse molestie consequat, vel ilium dolore eu 

feugiat nulla facilisis at vero eros et accumsan et iusto odio 

dignissim qui blandit praesent luptatum zzril delenit augue 

duis dolore te feugait nulla facilisi. 



lolore eu feugiat nulla 
luptatum zzril delenit 



onsequat, vel ilium dolore 
blandit praesent luptatum 
amet, consectetuer 
nagna aliquam erat 
er suscipit lobortis nisi ut 



Duis autem vi 

eu feugiat null 

zzril delenit ai 

adipiscing elit 

volutpat. Ut 

aliquip ex ea cornmodo consequat. 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt 
ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci 
tation ullamcorper suscipit lobortis nisi ut aliquip ex ea cornmodo consequat. Duis autem vel eum 
inure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla 
facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit 
augue duis dolore te feugait nulla facilisi. 

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex 
ea cornmodo consequat. Duis autem vel eum inure dolor in hendrent in vulputate velit esse molestie 
consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim 



v 



Done 



Figure 23-4: Elements using the fixed positioning model are positioned relative to the view 
port, much like absolute positioning. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



374 Part III ♦ Controlling Presentation with CSS 



Itt Div Positioning - Mozilla Firebird 



- as 



File Edit View Go Bookmarks Tools Help 



u 



'*"<* tfe 



http://localhost/Criapter23/Fig23-5.html 



< 



iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla 
facilisis at vero eros et accurnsan et iusto odio dignissirn qui blandit praesent luptatum zzril delenit 
augue duis dolore te feugait nulla facilisi. 

Duis autem v el eum inure dolor in hendrerit in vulputate velit esse molestie c onsequat, vel ilium dolore 



eu feugiat null 
zzril delenit ai 
adipiscing elit 
volutpat. TJt 
aliquip ex ea 



Loremipsum 
ut laoreet dol 
tation ullamcc 



Ut wisi enirn ad rninirn veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea cornrnodo 
v consequat. Duis autem vel eum iriure dolor in hendrerit in 
vulputate velit esse molestie consequat, vel ilium dolore eu 
feugiat nulla facilisis at vero eros et accurnsan et iusto odio 
dignissirn qui blandit praesent luptatum zzril delenit augue 
duis dolore te feugait nulla facilisi. 



blandit praesent luptatum 
amet, consectetuer 
nagna aliquam erat 
er suscipit lobortis nisi ut 



! nibh euismod tincidunt 
i, quis nostrud exerci 

LpLl SUSLipiL lUUUlUi 111J1 UL UliqUip LA LCI LU11U11UUU LUllSLqUUL. DlUS aUtem Vel CUm 

inure dolor in hendrerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla 
facilisis at vero eros et accurnsan et iusto odio dignissirn qui blandit praesent luptatum zzril delenit 
augue duis dolore te feugait nulla facilisi. 

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex 
ea cornrnodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie 
consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et accurnsan et iusto odio dignissirn 
qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. 

Duis autem vel eum inure dolor in hendrent in vulputate velit esse molestie consequat, vel ilium dolore 
eu feugiat nulla facilisis at vero eros et accurnsan et iusto odio dignissirn qui blandit praesent luptatum 
zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsurn dolor sit amet, consectetuer 



Done 



- 



Figure 23-5: Elements using the fixed positioning model do not scroll in the view port, as 
shown when this document scrolls. 



Note 



Not all user agents support all the positioning models. Before relying upon 
a particular model in your documents, you should test the documents in your 
target user agents. The properties supported by various user agents are covered 
in Appendix B. 



Specifying Element Position 



Element positioning can be controlled by four positioning properties: top, right, 
bottom, and ri ght. The effect of these properties on the element's position is 
largely driven by the type of positioning being used on the element. 

The positioning properties have the following format: 



side: length | percentage 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 375 



The specified side of the element is positioned according to the value specified. If the 
value is a length, the value is applied to the reference point for the positioning model 
being used — the element's normal position if the relative model is used, the view 
port if the absolute or fixed model is used. For example, consider the following code: 

position: relative; 
right: 50!S; 

These settings result in the element being shifted to the left by 50% of its width, as 
shown in Figure 23-6. This is because the user agent is told to position the right side 
of the element 50% of where it should be. 



(■"'j Div Positioning - Mozilla Firebird 



- nQ 



File Edit View Go Bookmarks Tools Help 



H 



' ® "^fr U fe I http://localhost/Ch apter23/Fig23-6.html 



K 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel eum inure dolor in 
hendrent in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros 
et accumsan et msto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait 
nulla facilisi. 



isi enirn ad minim veniam, quis nostrud exerci tation 
icorper suscipit lobortis nisi ut aliquip ex ea commodo 
equat. Duis autem vel eum inure dolor in hendrent in 
itate velit esse molestie consequat, vel ilium dolore eu 
at nulla facilisis at vero eros et accumsan et lusto odio 
ssim qui blandit praesent luptatum zzril delenit augue 
dolore te feugait nulla facilisi. 



ate velit esse molestie consequat, vel ilium dolore eu 
odio dignissim qui blandit praesent luptatum zzril 
m ipsum dolor sit amet, consectetuer adipiscing elit, 
dolore magna aliquam erat volutpat. Ut wisi enim 
per suscipit lobortis nisi ut aliquip ex ea commodo 



Done 



Figure 23-6: A rel at i ve, 50% right value results in an element being shifted to the 
left by 50% of its width. 



However, if the following settings are used, the element is positioned with its right 
side in the middle of the view port, as shown in Figure 23-7: 

position: absolute; 
left: b0%; 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



376 Part III ♦ Controlling Presentation with CSS 



Hit Diw Positioning - Mozilla Firebird 



- n0 



File Edit View Go Bookmarks Tools Help 



^ 



T ^- T *^ t ^ | http://localho st/Chapter23/Fig23-7.html 



L^J 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diarn nonurnrny nibh euismod tincidunt ut 
laoreet dolore magna aliquarn erat volutpat. Ut wisi erurn ad minirn veniam, quis nostrud exerci tation 
ullamcorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis auteni vel eurn inure dolor in 
hendrent in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros 
et accurnsan et iusto odio dignissirn qui blandit praesent luptaturn zzril delenit augue duis dolore te feugait 
nulla facilisi. 



Duis autern vel eurn inure dolor in hendrent in vulput 
feugiat nulla facilisis at vero eros et accurnsan et iust< 
delenit augue duis dolore te feugait nulla facilisi. Lore 
sed diarn nonurnrny nibh euismod tincidunt ut laoreet 
ad rninirn veniarn, quis nostrud exerci tation ullamcor 
consequat. 



Ut wisi enirn ad rninirn veniam, quis nostrud exerci tati 
ullamcorper suscipit lobortis nisi ut aliquip ex ea comn 
consequat. Duis autem vel eurn inure dolor in hendren 
vulputate velit esse molestie consequat, vel ilium dolor 
feugiat nulla facilisis at vero eros et accurnsan et iusto 
dignissim qui blandit praesent luptaturn zzril delenit au^ 
duis dolore te feugait nulla facilisi. 



< 



] i 



Done 



Note 



Figure 23-7: An absol ute, 50% 1 eft value results in an element being shifted so 
its left side is in the middle of the view port. 

Here, the user agent references the positioning against the view port, so the 
element's right side is positioned at the horizontal 50% mark of the view port. 

Positioning alone can drive the element's size. For example, the following code 
will result in the element being scaled horizontally to 25°/o of the view port, 
the left side positioned at the 25°/o horizontal mark, and the right at the 50% 
horizontal mark. 

position: absolute; 
left: 25% ; right: 50%; 

However, whichever property appears last in the definition drives the final size 
of the element. For example, the following definition will result in an element 
that has its left side positioned at the view port's horizontal 25% mark, but is 
300 pixels wide (despite the size of the view port): 

position: absolute; 
left: 25%; right: 50%; 
width: 300px; 

The wi dth overrides the right setting due to the cascade effect of CSS. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 377 



Floating Elements to the Left or Right 

The other way to position elements is to float them outside of the normal flow of 
elements. When elements are floated, they remove themselves from their normal 
position and float to the specified margin. 

The fl o a t property is used to float elements. This property has the following format: 

float: right | left | none; 

If the property is set to right, the element is floated to the right margin. If the 
property is set to left, the element is floated to the left margin. If the property is set 
to none, the element maintains its normal position as per the rest of its formatting 
properties. If the element is floated to a margin, the other elements will wrap around 
the opposite side of the element. For example, if an element is floated to the right 
margin, the other elements wrap on the left side of the element. 

For example, the image in Figure 23-8 is not floated and appears in the normal flow of 
elements . The same image is floated to the right margin (via the style float: right) 
in Figure 23-9. 



tf) Non-Floated Images - Mozilla Firebird 



- -10 



File Edit View Go Bookmarks Tools Help 



@ T ^ T *^f $ fe | http ://localhost/Chapter23/Fig23-3.html 



BK 



Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed diarn nonurnrny nibh euisrnod tincidunt ut 
laoreet dolore magna aliquarn erat volutpat. Ut wisi enirn ad minim veniarn, quis nostrud exerci tation 
ullarncorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel eum inure dolor in 
hendrent in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et msto odio dignissim qui blandit praesent luptatum zznl delenit augue duis dolore te feugait nulla 
facilisi. 

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullarncorper suscipit lobortis nisi ut aliquip ex ea 



commodo consequat. Duis autem vel eum inure ^^ dolor in hendrent in vulputate velit esse molestie 
consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et accumsan et msto odio dignissim qui 
blandit praesent luptatum zznl delenit augue duis dolore te feugait nulla facilisi. 

Duis autem vel eum inure dolor in hendrent in vulputate velit esse molestie consequat, vel ilium dolore eu 
feugiat nulla facilisis at vero eros et accumsan et msto odio dignissim qui blandit praesent luptatum zznl 
delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, sed 
diam nonurnrny nibh euismod tincidunt ut laoreet dolore magna aliquarn erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullarncorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. 



Figure 23-8: A nonfloated image is rendered where its tag appears. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



378 Part III ♦ Controlling Presentation with CSS 



C' tf ':J Floated Images - Mozilla Firebird 






File Edit View Go Bookmarks Tools Help 



^ 



©-«-£ .*t>l 



http://localhost/Chapter23/Fig23-9.html 



^ 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonurnrny nibh euisrnod tincidunt ut 
laoreet dolore magna aliquarn erat volutpat. Ut wisi enirn ad minim veniam, quis nostrud exerci tation 
ullarncorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel eum inure dolor in 
hendrent in vulputate velit esse rnolestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et msto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla 
facilisi. 

Ut wisi enim ad rninim veniam, quis nostrud exerci tation ullarncorper suscipit lobortis nisi ut aliquip ex ea 
commodo consequat. Duis autem vel eum inure dolor in hendrent in vulputate velit esse rnolestie consequat, 
vel ilium dolore eu feugiat nulla facilisis at vero eros et accumsan et msto odio dignissim qui blandit 
praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. 

Duis autem vel eum inure dolor in hendrent in vulputate velit esse rnolestie consequat, vel ilium dolore eu 
feugiat nulla facilisis at vero eros et accumsan et msto odio dignissim qui blandit praesent luptatum zzril 
delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed 
diam nonurnrny nibh euismod tincidunt ut laoreet dolore magna aliquarn erat volutpat. Ut wisi enim ad minim 
veniam, quis nostrud exerci tation ullarncorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. 



Done 



Figure 23-9: An image that is floated is removed from the normal flow and is 
moved to the specified margin (in this case, the right margin), and the other 
elements wrap on the exposed side of the element. 




If you don't want elements to wrap around a floated element, you can use 
the cl ear property to keep the element away from floaters. See the Clear- 
ing floating objects section in Chapter 19 for more information on the clear 
property. 



Defining an Element's Width and Height 

There are multiple ways to affect an element's size. You have seen how other 
formatting can change an element's size — in the absence of explicit sizing instructions 
the user agent does its best to make everything fit. However, if you want to intervene 
and explicitly size an element, you can. The following sections show you how. 



Specifying exact sizes 



You can use the width and height properties to set the size of the element. For 
example, if you want a particular section of the document to be exactly 200 pixels 



PI: JYS 

WY022-23 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 379 



wide, you can enclose the section in the following <d i v > tag: 

<div style="width: 200px;"> ... </div> 

Likewise, if you want a particular element to be a certain height, you can specify the 
height using the height property. 

Note Keep in mind that you can set size constraints— minimum and maximum 

sizes— as well as explicit sizes. See the next section for details on minimum 
and maximum sizes. 

Specifying maximum and minimum sizes 

There are properties to set maximum and minimum sizes for elements as well as 
explicit sizes. At times, you will want the user agent to be free to size elements by 
using the formatting surrounding the element, but still want to constrain the size, 
allowing an element to be displayed in its entirety instead of being clipped or 
displayed in a sea of white space. 

You can use the following properties to constrain an element's size: 

♦ mi n-wi dth 

♦ max-width 

♦ mi n-hei ght 

♦ max-hei ght 

Each property takes a length or percentage value to limit the element's size. For 
example, to limit the element from shrinking to less than 200 pixels in height, you 
could use the following: 

mi n-hei ght: 200px; 



Controlling element overflow 



Whenever an element is sized independently of its content, there is a risk of it 
becoming too small for its content. For example, consider the paragraphs in 
Figure 23-10 — the paragraphs are the same except that the second paragraph has 
had its containing box specified too small, and the contents fall outside of the border. 

In this example the user agent (Opera) chose to display the rest of the element 
outside its bounding box. Other user agents may crop the element or refuse to 
display it at all. 

If you want to control how the user agent handles mismatched elements and content 
sizes, use the o v e rfl ow property. This property has the following format: 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



380 Part III ♦ Controlling Presentation with CSS 



w'l Elements too Small - Mozilla Firebird 



- n £ 



File Edit View Go Bookmarks Tools Help 



U 



- *-tf .$> 



http://localhost/Criapter23/Fig23-10.html 



< 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonurnmy rubh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullarncorper suscipit lobortis nisi ut aliquip ex ea cornmodo consequat. Duis autem vel eum iriure dolor 
in hendrerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero 
eros et accumsan et lusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te 
feugait nulla facilisi. 



Lorem ipsum 
dolor sit amet, 
consectetuer 
adipiscing elit, 
;ed diam 



nonummy nibh 
euismod 
tincidunt ut 
laoreet dolore 
magna aliquam 
erat volutpat. Ut 



wisi enim 



ad 



minim veniam, 



Done 



Figure 23-10: An element that is mis-sized doesn't always handle its content properly. 



overflow: visible | hidden | scroll | auto; 
The values have the following effect: 

♦ v i s i bl e — The content is not clipped, and is displayed outside of its bounding 
box, if necessary (as in Figure 23-10). 

♦ h i dden — If the content is larger than its container, the content will be clipped. 
The clipped portion will not be visible, and the user will have no way to access it. 

♦ scroll — If the content is larger than its container, the user agent should 
contain the content within the container, but supply a mechanism for the 
user to access the rest of the content (usually through scroll bars). Figure 23-11 
shows the same paragraph as in Figure 23-10, but with its o v e rfl ow property set 
to scroll. 

♦ auto — The handling of element contents is left up to the user agent. Overflows, 
if they happen, are handled by the user agent's default overflow method. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 381 



!? r j Elements too Small - Mozilla Firebird 



- -i El 



File Edit View Go Bookmarks Tools Help 



t $—*& gt6 



http://localhost/Chapter23/Fig23-1 1 .html 



Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut 
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation 
ullarncorper suscipit lobortis nisi ut aliquip ex ea commodo consequat. Duis autem vel eurn iriure dolor in 
hendrerit in vulputate velit esse molestie consequat, vel ilium dolore eu feugiat nulla facilisis at vero eros et 
accumsan et msto odio dignissim qui blandit praesent luptaturn zzril delenit augue duis dolore te feugait 
nulla facilisi. 



veniam, quis 


w 


nostrud 




exerci tation 




ullarncorper 




suscipit 


1 


<J mi [_> 



Done 



Figure 23-11: The overflow property set to scroll instructs the user agent to supply a 
mechanism to view the entire content (usually scrollbars). 



Stacking Elements in Layers 



Using CSS positioning can often lead to elements stacked on top of one another. 
Usually, you can anticipate how the elements will stack and leave the user agent up 
to its own devices regarding the display of stacked elements. At times, however, you 
will want to explicitly specify how overlapping elements stack. To control the 
stacking of elements, you use the z - i ndex property. 

The z - i ndex property has this format: 



z - i n d e x : 



val lie; 



The property controls the third dimension of the otherwise flat HTML media. 
Because the third dimension is typically referred to along a Z axis, this property is 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



82 Part III ♦ Controlling Presentation with CSS 



named accordingly (with a Z). You can think of the z-stack as papers stackedon a 
desktop, overlapping each other — some of the papers are covered by other pieces. 

The value controls where on the stack the element should be placed. The beginning 
reference (the document) is typically at index (zero). Higher numbers place the 
element higher in the stack, as shown in the diagram in Figure 23-12. 



Index: 3 



Index: 2 



Index: 1 





Document 
(Index: 0) 



Figure 23-12: The effect of the zindex property. 



A practical example of z - i ndex stacking can be seen in Figure 23-13. Each element is 
assigned a z-index, as shown in the following code: 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN 

"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

< t i 1 1 e > Z - index Stack ing</title> 
<style type="text/css"> 

. b o x 1 i position: absolute; 
top: 25Z; left: 25%; 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 383 



wi dt 



,box2 



ad 
la 

mi 
lo 
ve 

"Q 

fa 
qu 
do 



</styl 

head) 
ody> 
i v c 1 a 
><b>Bo 
i p i s c i 
oreet 
n i m v e 
b o r t i s 
1 eum 
1 e s t i e 
c i 1 i s i 
i b 1 a n 
1 ore t 



ith 
:kg 
1 or 
i nd 
ith 
:kg 
i nd 

.box3 { width 
backg 
posit 



ba 

CO 

z- 

wi dt 
ba 

z- 



ss="bo 
x 2:</ 

n g e 1 i 

dol ore 
n i a m , 

nisi 
i r i u r e 

conse 
s at v 
d i t p r 
e f eug 



i >' d 



x2" 

b> 

t, 

~a 
qui 
ut 

do 
qua 
ero 
aes 
ait 



: 200px; height: 200px; 

round -color: red ; 

: white; 

ex: 200; ) 

: 400px; height: 400px; 

round -color: yel 1 ow; 

ex: 100; ) 

: 400px; height: lOOpx; 

round -col or : green ; 

ion: absolute; 

2035; left: 10SS; color: white; 

ex: 150; 1 



Lorem ipsum dolor sit amet, consectetuer 
sed diam nonummy nibh euismod tincidunt ut 
gna aliquam erat volutpat. Ut wisi enim ad 
s nostrud exerci tat ion ullamcorper suscipit 
aliquip ex ea commodo consequat. Duis autem 
lor in hendrerit in vulputate velit esse 
t, vel ilium dolore eu feugiat nulla 

eros et accumsan et iusto odio dignissim 
ent luptatum zzril delenit augue duis 

nulla f a c i 1 i s i . < / p > 



'p class="boxl' 



3ox l:</b> This is text</f 



>Ut wi 
1 amcor 
nsequa 
1 putat 
u g i a t 
i o dig 
gue du 
lor si 
rummy 
i q u a m 
di v> 
i v c 1 a 
<p><b> 
di v> 
body) 
html) 



si enim ad minim veniam, quis nostrud exerci tat ion 
per suscipit lobortis nisi ut aliquip ex ea commodo 
t. Duis autem vel eum iriure dolor in hendrerit in 
e velit esse molestie consequat, vel ilium dolore eu 
nulla facilisis at vero eros et accumsan et iusto 
nissim qui blandit praesent luptatum zzril delenit 
is dolore te feugait nulla facilisi. Lorem ipsum 
t amet, consectetuer adipiscing el it, sed diam 
nibh euismod tincidunt ut laoreet dolore magna 
erat vol utpat . </p> 

ss="box3"> 

Box 3:</b> This is text.</p> 



The code uses a mix of <di v> and <p> elements for diversity. Since boxl's index is 
the highest (200), it is rendered on the top of the stack. Box3's index is the next 
highest (150), so it is rendered second to the top. Box2's index is the lowest (100), so 
it is rendered near the bottom. The document itself is recognized as being at 0, so it 
is rendered at the bottom of the stack. 



If you change the z - i ndex of boxl to 125, it will render under box3, as shown in 
Figure 23-14. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



384 Part III ♦ Controlling Presentation with CSS 



ME) Z-index Slacking - Mozilla Firebird 



BlgJB 



File Edit View Go Bookmarks Tools Help 



@ *■ $< -tg ^Jj | h1tp://locaihos t/Chap1er23/F ig23-13.html 



1^ 



Box 2: Lorern ipsum dolor sit atnet, consectetuer adipiscing elit, 

sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna 

aliquam erat volutpat. Ut wisi enim ad minim veniarn, quis nostrud 

exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex ea 

commodd 

in vulputai:- 

feugiat nu 

dignissiml 

dolore te I 

Ut wisi enim ad minim \ 

ullamcorper suscipit lob oil 

consequat. Duis autem; 

velit esse molestie conseqJ 

facilisis at vero eros et ace 

praesent luptatum zzril del J 

facilisi. Lorem ipsum dolor^H^^^^^^^^H^HH^^^^ elit, 

sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna 

aliquam erat volutpat. 




Done 



Figure 23-13: A sample of zi ndex stacking. 



Tip 



You can use many of the properties in this chapter for animation purposes. 
Using JavaScript, you can dynamically change an element's size, position, and/or 
z-index to animate it. For more information, see Chapters 25 and 26. 



Controlling Element Visibility 



Note 



You can use the visibility property to control whether an element is visible or 
not. The visibility property has the following format: 

visibility: visible | hidden | collapse; 

The visible and hidden values are fairly self-explanatory — set to visible 
(default), an element is rendered; set to hidden, the element is not rendered. 

Even though an element is hidden with vi si bi 1 i ty, set to hi dden it wil 
still affect the layout— space for the element is still reserved in the layout. 



PI: JYS 
WY022-23 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



Chapter 23 ♦ Element Positioning 385 



UEjZ-index Stacking - Mozilla Firebird 



- n £ 



File Edit View Go Bookmarks Tools Help 



^ 



'f '- 






http://localhost/Chapter23/Fig23-14.html 



v 



Q. 




Box 2: Lorem ipsum dolor sit arnet, consectetuer adipiscing elit, 

sed diarn nonummy rabh euismod tincidunt ut laoreet dolore magna 

aliquarn erat volutpat. Ut wisi enim ad minim veniam, quis nostrud 

exerci tation ullamcorper suscipit lobortis nisi ut aliquip ex ea 

commodd 

in vulputalt 

feugiat nu 

dignissiml 

dolore te 

Ut wisi enirn ad minim ve: 

ullamcorper suscipit lobo; 

consequat. Duis autemvelj 

velit esse molestie conseqi 

facilisis at vero eros et ac 

praesent luptatum zzril deli 

facilisi. Lorem ipsum dolo: 

sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna 

aliquam erat volutpat. 




Done 



Figure 23-14: Changing an element's z-i ndex changes its position in the stack. 

The col 1 apse value causes an element with rows or columns to collapse its borders. 
If the element does not have rows or columns, this value is treated the same as hidden. 

Cross- For more information on collapsing borders, see Chapter 22. 

Reference 



Summary 



HTML documents formatted with CSS can produce dramatic results. Previous 
chapters showed you how to format individual elements, and this chapter showed 
you how to position elements in all three dimensions. Chapter 24 shows you how to 
format your documents for printing, truly bridging online and print media. 



PI: JYS 

WY022-23 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:52 



386 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



Defining Pages 
for Printing 



Have you ever printed a Web page and been amazed 
at just how badly the page printed? All kinds of nasty 
things can happen. The most annoying is probably when the 
text runs off the left side of the page, but there are other 
annoyances, as well. The Web, after all, was originally intended 
as a browsing medium. And although researchers who use the 
Web and write simple HTML pages can always be counted on 
to format their HTML in a way that makes their pages suitable 
for printing (largely because they simply eschew bells and 
whistles), those of us with an eye for design tend to run into 
some problems. 

This problem is less common on today's modern Web, partly 
because CSS allows Web authors to control the way a page 
looks in print. You might not even notice that a Web page 
contains very specific formatting instructions when simply 
viewing it in a browser, because many of the properties 
associated with print-based formatting are not designed to 
appear in the browser, but instead provide instructions as to 
how the printer should manage the flow of a page. 

This chapter takes a look at how to use CSS to pass 
instructions to the printer to make your Web pages look more 
readable. CSS support for printed media is not particularly 
strong yet, but it gains with each new browser version, so it's 
worth taking a look at (even those CSS properties that don't 
yet have full browser support). 







♦ ♦ ♦ ♦ 

In This Chapter 

The Page Box Formatting 
Model 

Defining the Page Size 

Setting Margins 

Controlling Page Breaks 

Handling Widows and 
Orphans 

Preparing Documents for 
Double-Sided Printing 



The Page Box Formatting Model 

If you've ever worked with a desktop publishing platform using 
software such as Quark XPress, InDesign, or PageMaker, you're 
probably familiar with the concept of a page box, within which 
fits everything that must go on a page. Even if you haven't 
worked with desktop publishing software, you've probably 



387 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



388 Part III ♦ Controlling Presentation with CSS 



seen precursors to the Web's page box formatting model in word processing 
packages you've used. 

When you work in a word processing or desktop publishing environment, you work 
with finite page sizes and page margins. The CSS page box formatting model is an 
attempt to replicate this for browser-based media. The page box model is based on 
the CSS box model (introduced in Chapter 16), as shown in Figure 24-1. 



Left 



Top 

margin-top 





border-top 


border-left 

r 

padding-left 


padding-top padding 
Content 

padding-bottom 


padding-right 
border-right 


border-bottom 



Right 



margin-bottom 
Bottom 



page edge 
= margin edge 
= border edge 
= padding edge 

= content 



Figure 24-1 : The CSS box model. 



P1:KTX 

WY022-24 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



Chapter 24 ♦ Defining Pages for Printing 389 



Figure 24-1 simply extends the box model to reveal two major areas: 
♦ The page area, which contains all of a page's elements. 

4- The margin area, which surrounds the page area. When a page area size is 
specified, the margins, if any, are subtracted. 

On top of the page box, the model is expanded still further to account for the 
difference between continuous media, as represented by a browser, and paged media, 
which consists of discrete and specific page entities. This expansion is represented 
by the visual formatting model, which allows transfer of the continuous media as 
seen in a Web browser to an actual sheet of paper or transparency (or even film). 

Defining the Page Size with the @page Rule 

In word processing and desktop publishing environments, you define a page size by 
using a dialog box within a set-up option of some kind. In CSS, you define the size of a 
page using the ©page rule. The ©page rule defines which pages should be bound to 
the definitions within the rule. You then use a pa ge property within a style element 
or attribute to indicate which page a specific element belongs to. 

Unfortunately, browser support has still not caught up to this particular CSS rule, 
and support is pretty nonexistent at this point. Microsoft actually does provide 
support for this rule, but only through the MSHTML component, which application 
developers use as a browser widget within their applications. Internet Explorer itself 
does not include support for this rule in its printing templates, which are used for 
print previewing and printing Web documents from the browser. If you're a 
programmer, you can find more information on how you can override this behavior 
at this address: http://msdn.microsoft.com/workshop/browser/hosting/ 
hosti ng . asp. 

Listing 24-1 demonstrates how the ©page rule works. 

Listing 24-1 : Using an @page Rule to Set up Page Size 

<style type="text/css"> 

<!-- 

@page printed! 

size: 3 i n 3 i n ; 
margin: . 5in; 
page-break-after: left; 

body, p 1 

page: printed 

width: 600px; 
widows: 1; 
page-break-after: right; 



(/style) 



P1:KTX 

WY022-24 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



390 Part III ♦ Controlling Presentation with CSS 



In Listing 24-1, a page named "printed" is defined. Then, HTML elements that are 
defined in the stylesheet using pri nted within the page property should emerge 
from the printer according to the specifications outlined in the @p a g e rule: 

body, p 1 

page: printed 
width: 600px; 
widows: 1; 
page-break-after: right; 



In CSS2, page selectors can be used to name the first page, all left pages, all right 
pages, or a page with a specific name that the rules apply to. In the case of Listing 
24-1, a named page called pri nted was used. 

Setting up the page size with the size property 

The actual dimensions of the page are defined using the size property, also shown 
in Listing 24-1. The size property consists of two absolute values, one for the width 
and the other for the height. So the following translates into an 81/2 x 11 size page: 

@page { 

size: 8 . 5 i n 1 1 i n ; 



You can also use the following relative size values: 

♦ a u t o is the default value and is whatever the target paper size is in your 
printer's settings. 

♦ landscape flip flops the dimensions named in the size property so that in 
the previous example, the printed sheet would print out at 1 1 inches wide by 
8 inches deep. 

♦ portrait overrides the targeted media's default settings to correspond with 
the dimensions you set in the size property. 



Setting margins with the margin property 

In general, you need to be careful when using margins because they are the 
outermost layer of a page. If you set the margins of a body element to three inches 
on either side, for example, be sure to set the width of that same body element as 
well, or your page will look like that shown in Figure 24-2. 

However, in theory you should be able to set margins for the printed page without 
worrying about the body text running off to one side of the browser when you 
neglect to set the width of the page's other elements. 

This is because margins can be set using the margin property in CSS within an @pa ge 
rule. Margins were covered in Chapter 20, Padding, Margins, and Borders. You can set 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



Chapter 24 ♦ Defining Pages for Printing 39 1 



: File Edit View Favorites Tods Help 


• 


1 o • o ■ a a 6 


PiV«© £ - §* ^ - D ® & 


i 


] Address ^] C : '.Documerte and Settinge\Chuck\Book\Wiey\Ch25',margine.itrn 


ZZ\B^ 



myp ontC 1 as s { f ont - i ami ly : Arial, Helvetica, sans-serif} 

Using this font will render a sans -serif font on the vast majority of mo d=m brows ei 

To understand what afon: family is, consider what a font family is not. Helvetica a 
Narrow do no: constitute a font family, even though it's reasonable to suspect they " 
the same family. Helvetica Narrow, by itself, is a font family. So is Helvetica, whia 
a basic kind of Helvetica font. There is also Helvetica Condensed, and other vana 

Understanding 
fonts and font 
availability 

The first thing to understand about font a^ailabilry is that they probably aren't. In e 
your best laid plans when it comes to your design are likely to endup in complete 
The reason? Tie fonts you name in a CSS Ee may, or may not, be on your users' 
systems. 

There ere a few ways to ensure, for CKsmiplc, that Ansil. or Helvetia will appesir i 
vour web nsiae for most of vour audience. But that's sib out it. Other than those twf v 

> 



^) Done 

Figure 24-2: Bad margins. 



J My Computer 



the page margins, as shown in Listing 24-1, by simply using the margin property in 
the same manner as you use it anywhere else, as shown here: 



Opage 1 

size: 3 i n 3 i n ; 

margin: . 5in; 

page-brea k-af ter : 



left; 



The margin settings should be ignored when being viewed on the Web when they're 
set in an @pa ge rule. However, once again, at the time of this writing, browser 
support for this feature is weak. 



Controlling Page Breaks 



Another way to control the flow of a printed page is to force page breaks before or 
after named elements. There's good news here. Browser support is actually pretty 
decent (see Table 24-1). 

You can set the page- brea k- before or page -break- after property in a p 
element, for example, to force a page break before or after all p elements. You 
probably wouldn't want to actually do that unless you have awfully long paragraphs, 



P1:KTX 

WY022-24 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



392 Part III ♦ Controlling Presentation with CSS 



but you can create a class selector rule and apply the rule to the first or last 
paragraph of a page, depending on your needs, like this: 

pagebreak 

page-break-before: always; 

In this case, then, you simply apply it to a head element of a page: 

<h2 cl ass="pagebrea k">How the Panose System Works</h2> 

Note that you can't use page breaks within positioned elements. This means that if 
you have an absolutely positioned di v element with a child p element and the p 
element has a page break assigned to it via a CSS rule, it won't work. 

Using the Page-Break Properties 

When your users wish to print your pages, you may want to avoid starting pages 
with a few lines from a paragraph that started on a previous page. The way to 
accomplish this is with a CSS page-break property. There are three of them: 

♦ The page- break- before property specifies how a page should break after a 
specific element, and on what side of the page the flow should resume. 

4 The page- break- after property specifies how a page should break before a 
specific element, and on what side of the page the flow should resume. 

♦ The page-break- inside property tells the browser how to break a page from 
within a box element. Actual support for this property is limited to Opera 3.5. 
Neither Internet Explorer nor Netscape browsers support this property. 

If you don't have a lot of headings, you can set up a style rule and call a page-break 
property using an element's class attribute. Browser support is strongest in 
Opera 3.5 and above. 

Using the page-break-before and 
page-break-after properties 

The page -break -before and page- break- after properties specify how a page 
should break before or after a specific element, depending on which of the two 
properties you use, and on what side of the page the flow should resume. The CSS2 
documentation provides these general guidelines: 

4 Page breaking should be avoided inside table elements, floating elements, and 
block elements with borders. 

4 Page breaking should occur as few times as possible. In other words, it's not a 
good idea to break a page with every paragraph. 

4 Pages that don't have explicit breaks should be approximately the same height. 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



Chapter 24 ♦ Defining Pages for Printing 393 



Once again, the best support for this property is in the Opera browser. 

Internet Explorer also supports page-break properties, particularly the a 1 ways 
value. In fact, in Internet Explorer, the left and right values are treated as if they 
are a 1 way s. In addition, Internet Explorer ignores this property when used with h r 
and b r elements. Table 24-1 lists the values that can be used with either the 

page-break-before or page-break-after property. 



Caution 



Even though Opera is designed to support the inherit property value, some 
bugs have been reported on this feature indicating that Opera will often crash 
on pages using this value. 



In Table 24-1, the browser support can be assumed to be true for versions following 
the one named for each specific browser, unless an inconsistency or bug is noted in 
the description. 





Table 24-1 
Page-Break-Before/After Property Values 




Value 


CSS Version 


Description 


Browsers 


inherit 


2 


Specifies that the value should be 
inherited from the parent 


None 


auto 


2 


Allows the user agent (browser) to insert 
page breaks on an as-needed basis 


IE4, Netscape 7, 
Opera 3.5 


avoid 


2 


Tells the user agent to avoid inserting 
page breaks before or after the current 
element 


Opera 3.5 


left 


2 


Forces one or two page breaks to create 
a blank left page 


IE4, Opera 3.5 


right 


2 


Forces one or two page breaks to create 
a blank right page 


IE4, Opera 3.5 


always 


2 


Tells the browser or user agent to always 
force a page break before or after the 
current element 


IE3, Netscape 7, 
Opera 3.5 



NA This is not a value found in the spec but 

is actually a value that can be used in 
Internet Explorer; it explicitly specifies 
that no property value should be used, 
and therefore, no page break should be 
inserted before the current element 



IE5 



Listing 24-2 shows how the page- break- before property is used in ahead element 
(H2) to help ensure that a page starts with a head element instead of a few lines of 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



394 Part III ♦ Controlling Presentation with CSS 



dangling paragraph text. Figures 24-3 and 24-4 show how the effect appears in a Print 
Preview screen in Internet Explorer. Note that the figures represent the rendered 
page as it would look with all the source code intact (Listing 24-2 was snipped to 
save space). 

Listing 24-2: Using the Page-Break-Before CSS Property 



<html> 

<head> 

<title>Printing with CSS</title> 

<meta http -equi v="Content -Type" content="text/html ; 

charset=i so -8859-1") 

<style type="text/css"> 

p . code { 

font-family: "Courier New", Courier, mono; 
font-size: llpx; 
background -col or : #CCCCCC; 
padding: 3px; 

.pagebreak { 

page-break-before: always; 
} 

. i n 1 i n e c o d e { 

font-family: "Courier New", Courier, mono; 



</styl 


</head 


<body> 


<hl>Un 


<p>Whe 


unders 


and He 


<!-- C 


</p> 


<h2 cl 


<p>Pan 


<!-- C 


</p> 


<h2>Wo 


<p>In 


font t 


using 


or < 


<!-- C 


<!-- M 


</body 


</html 



derstanding Font families</hl> 

n choosing font families for style sheets it helps to 

tand some basic facts about fonts. For example, Aria! 

Ivetica are virtually identical. 

ode snipped to save trees - - > 

ass="pagebreak">How the Panose System Works</h2> 
ose is a system of font substitution that uses... 
ode snipped to save trees - - > 

rking with Font styles</h2> 

traditional HTML you can choose whether you want your 

o appear in Roman style (non-italic) font or italics by 

or not using the <span cl ass="i nl i necode">em</span> 

span cl ass="i nl i necode">i </span> el ements : </p> 

ode snipped to save trees - - > 

ore paragraphs here --> 



Figures 24-3 and 24-4 show how the Print Preview looks before applying the page 
break using the class attribute. Note the last heading on the first page in 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



Chapter 24 ♦ Defining Pages for Printing 395 



Pjje[r~|of2 "* * ift lft|7^ 



|tf| 

Hsl'^eti.ca, which ac:ually refers to a basj: j±idof Eetretka font. Tnere is also Hal^etica 
Cnn-lensed anrl fitter van ati nns 

I Jn ders t,\n f ling f i>« ts <n k 1 1 fan t a v ni I ii Iti Hi" v 

T.ie iiist thing 1o unders:ar.d about lout availal^ilyisttetttey probably aren't In cthar 
words, all yourbest laid plans itfher.it comes, to your design are likely to eaui up in :onvolete 
die appoint rcient The reason? Tne font? jcu name ir. a CSS fie may, cr may net, be on your 

UHJLi' UUKLUU.JBJ B'/KfclilH 

Tne:e are a fe w ways :o a nsure . for example, that Ariel or Helve tka *ril appear as e::pec :et 
on your vreb page for most of your audie nee . But that's about i1. Other than those tiro fents, 
if s either a ciap snost or a lo: of j imping thiougl. fon: hocpe to get your fonts to rencb r. The 
reason is simple, "f oucan ash your user's trewse: to as'olay. for axampja, the Wringer font, 
but flheir system doesn't haye itinstdled, the bmreer will simply display the nexl cjusest 
thing. How the bioivser dec ides tha:isste is in ajgcrilkmic pecess based or. some thing 
cdlcdthc PANIC E 3j3t in (sc; siebborj, hut the bottom line is tha: vjiirHTMLXoS docs 
iuj L embed any n; Lual fujLt-r.ubmLitiui.ur. fji.Ls. it njeiil ■/ JKLjues Is LJue bxu wksi Lu display t 
font if that font happens to be en the user's system. 

How llit Piiiiose Swiriii Works 

Bincse is a stsicivl of font substiritior. that uses a combination of mapping software (not as 
in world maps, but as Lnsoirware that mates celcula ted convoansons). atem-digitnunibering 
system, ami a classification me:hodto help the broker match font propary values. If Hal 
fails, the bioire?r tries to fine the closesl math. For ezanvole, if jou r.ame Furora Extra Bo Id 
oi the Dnly fcnl when you name o fonl family tsing cither CSS or the font cb incut's fac; 
attribute, and the user's system dcesn'1 hava Futuia Extra Bo^d installed, the browser will 
piobablyuse scrnathirg lite Anal blach because both loms are hea/y wide sans-sent'tbr.ts 

Working vvidi FouJ si vies 



fiJe:fJ^:UociJiT.enlsft20m^^ 12/1/2CO 



P 



Figure 24-3: You can use your browser's Print Preview to view how the page will 
look in print (Page 1). 



Kin:... |£|| «■ <f Pj3ef2~|ot2 ■* * | ift ift | /!:% v | ] Help] Llose 



L 



Fjiiitii^ wilhCSE Fa&e2 jf2 



In traditDnal Hl'Mb you can c .ions? whetne: yon want your tent tc appear in Kornan style 
(rn h-i-alic) fon - nr ira he s by nsi n^ or int nsiifr the =tt nr i FlftTifcnrr 



T.'ie pBcedins code fracr.manl ra suite in Sjc i^ ^bjo^T^j:: 

limnhasizins a pemt vnth the emitew&Tti or the lelen.ent. 

Tnc rcisonfcr ncving two clcmciLts is tint the en corac fimt and the i clcmcnl corns lalcr, 
andif youw^nl to reallybe sure even the earliestofb^j^sj; Kc^gnise you: ialics, em is 
the iyayiD gc. Mire importantly, if s a be tb r choice bee auseaoal browse :s should 
eiriTrhasi^e the rnntents of _ his elernenl to si frht-inrHi Ter users nf ynn v ush Hte 

Forties ^escn,tlisisone of tie :aie exceptions :o the nil; of usur^ C5S Jbi styling ever 
HTML element. Howe^r, tiere's nodiing vrcr^ vdtlmsing boti.Tc use ir. CSS, singly 
irrlid; the frl lnuHrp Hither inlne nr in a rule seleclnr 



B? sure lo ea!lit italic, not italics vrathar. s. Youeandso use font -style: 

Oi 1 1 que : but ullei veiKiuns uf ITeLa; a}je will iuj L JCLU^iLit iL, tu '/ui'm ^taLr^ yju .iiiiu 

EstablishiiLgFciit Sizes 

rvferaging font ease ^an he trichy 3V3 n with CSi,but nacctdevelcpercceena x; agree that the most 
icliabb uiu L uf u\b as ujbi:ib nt in C3 2 is Q\k pixel. [vkiLi^i.r^ : iijj.L si^s in a liaighl HTTvIL, aa JLU.edenliei 
m tr.e rhaplei, e abou: ^3 mesacta scier^e m there ls : buttha geneialrvie ns supposed to wcrh In^e this 
lite thatsrovTiinthe listir^ pnvidedeerljai in this chapter, Lst^g lS-2,whichslrjwsalltLe a^'ailable 
attribute valu?s fcr ttae fon: elements sise attribule . The way its supposed to work, btt oflen cbesnt is 
tliat uaii^ ttic I sjgr.bifore annuber, hhc 1 1 cr 1 2, imms ttic fcntb^gci ntlathie to tlie default font 
si7enn t'w ™?n In rnnrln rtir n mrim™ entr tliisisnnt ^ TelisVile rmw* Tf Tinn mint™ tlie fh^t 



Figure 24-4: Page two of the print preview using page-break-before shows 
the break occurring on the H2 element. 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



396 Part III ♦ Controlling Presentation with CSS 



Figure 24-3, which is at the end of the page and has no text under. This is because the 
page broke at a bad spot. Figures 24-5 and 24-6 show how the print previews look 
after the CSS has been fixed. 



3 Print Preview 



■» a &[?^ 



vl Help Close 



in. If you use the generic "sans-serif, you'll get the default sans -serif font on the user's 
svstem. So your best, lowest common denominator CSS font selector looks hke this: 



Using this font will render a sans-serif font on the vast majority of mode m browsers 

To understand what a font family is, consider what a font family is not. Helvetica and 
Helvetica Narrow do not constitute a font family, even though it's reasonable to suspect they 
would belong to the same family. Helvetica Narrow, by itself, is a font family. So is 
Helvetica, which actually refers to a basic kind of Helvetica font. There is also Helvetica 
Condensed, and other variations. 

Understanding fonts and font availability 

The first thing to understand about font availability is that they probably aren't. In other 
words, all your best laid plans when it comes to your design are likely to end up in complete 
disappointment. The reason? The fonts you name in a CSS file may, or may not, be on your 
useis' computer svstems. 

There are a few ways to ensure, for example, that AriaL or Helvetica will appear as expected 
on your web page for most of your audience. But that's about it. Other than those two fonts, 
ifs either a crap shoot or a lot of jumping through font hoops to get your fonts to render. The 
reason is simple. You can ask your user's browser to display, for example, the Frutiger font, 
but if their system doesn't have it installed, the browser will simply display the next closest 
thing. How the browser dec ides that issue is an algorithmic process based on something 
called the PANOSE system (see sidebar), but the bottom line is that your HTMUCSS does 
not embed any actual font information or fonts, it merely requests the browser to display a 
font if that font happens to be on the user's system. 



Figure 24-5: This page improves upon the page breaking in Figures 24-3 and 24-4 (Page 1). 



The page break in Listing 24-2 is handled through a class selector shown in bold, 
which is applied to an HI element, also in bold. 

Using the page-break-inside property 

You can alsousea page-break-i nside property to handle page breaks within 
elements (for example, if you have a very long d i v element). However, in practice, 
the only current browser support is in Opera 3.5 and higher. 



Handling Widows and Orphans 



Widows and orphans are normally tragic subjects, but CSS has provided developers 
an opportunity to reduce their impact. A widow is the number of lines at the top 
of a page. It can be unsightly if there is, for example, just one sentence at the top of 
a page before a section break. An orphan is similar, except it occurs at the end of a 
page. Again, it can be unsightly if a section or paragraph starts at the very end of 



P1:KTX 
WY022-24 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



Chapter 24 ♦ Defining Pages for Printing 397 



3 Print Preview 



Print.. 



«■ *■ PagehT~lof2 "* * & ©. ^ 



v| Help Close 






L 



Printing with CSS Page2of2 

How the Panose System Works 

Panose is a system of font substitution that uses a combination of mapping software (not as 
in world maps, but as in software that makes calculated comparisons), a ten-digit numbering 
system, and a classification method to help the browser match font property values . If that 
fails, the browser tries to find the closest match. For example, if you name Futura Extra Bold 
as the only font when you name a font family using either CSS or the font element's face 
attribute, and the user's system doesn't have Futura Extra Bold installed, the browser will 
probably use something lite Arial Black because both fonts are heavy, wide sans-serif fonts. 

Working with Font styles 

In traditional HTML you can choose whether you want your font to appear in Roman style 
(non-italic) font or italics by using or not using the em or i elements: 



The preceding code fragment results in this in a browser: 

Emphasizing a point with the emelement or the i element. 

The reason for having two elements is that the em came first, and the i element came later, 
and if you want to reallybe sure even the earliest of browsers recognize your italics, em is 
the way to go. More importantly its abetter choice because aural browsers should 
emphasize the contents of this element to sight-impaired users of your web site. 

For this reason, this is one of the rare exceptions to the rule of using CSS tor styling over 
HTML elements. However, there's nothing wrong with using both. To use in CSS, simply 
include the following either inline or in a rule selector: 




Figure 24-6: This page improves upon the page breaking in Figures 24-3 and 24-4 (Page 2). 

a page and the page break results in only a line or two of text at the very end of the 
page. 

One way to help control widows and orphans is through page-breaks. This is 
especially true since the two CSS properties that are relevant to widows and 
orphans, respectively named, conveniently enough, wi dow and orphan, have 
virtually no browser support beyond Opera. 

Both of these properties have similar syntax: 

widow: 4; 
orphan : 3 ; 

You name the property, then supply the value, which can either be an integer or the 
explicit value inherit, the latter of which means the element named in the style 
rule inherits the properties of its parent. The following sets a p element's widow to a 
minimum of three lines. This means that the bottom of the page must have a 
minimum of three lines when printing: 

<p STYLE="orphans : 3">This paragraph must not be on the top of a page by 
itself if it doesn't consist of at least three 
1 i n e s . < / p > 



If it doesn't, the entire block must be moved to the next page. 



P1:KTX 

WY022-24 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 10, 2004 8:53 



398 Part III ♦ Controlling Presentation with CSS 

Preparing Documents for 
Double-Sided Printing 

To set up pages for printing, you need to account for margin differences on each side 
of a double-sided, printed page. One way to handle that would be to set the margins 
differently for elements you expect to appear on different pages, but that would be 
ugly and almost impossible to do. The only other way is to use CSS @pa ge 
pseudo-classes named : 1 ef t and : right, and to set the margins of each differently. 
But, once again, the catch is that browser support is not yet there. 

For the curious among you, these pseudo-classes, working in tandem, look like this: 

@page : 1 ef t { 

margi n -1 ef t : . 5 i n ; 

margi n - ri ght : .25in; 
} 
©page : right { 

margi n -1 eft : . 2 5 i n ; 

margi n - ri ght : .5in; 

You can also specify style for the first page of a document with the : fi rst 
pseudo-class: 

@page 1 margin: lin I 
@page :first { 

margin-top: 3in 
} 

The preceding code sets all the margins at one inch, but the top margin of the first 
page at three inches, thus overriding the overall page margins established by the 

first ©page rule. 



Summary 



As you can see, printed page management within the CSS realm still has a way to go 
in terms of browser support, which is why we focused most of our attention on the 
one area that has a comparatively high degree of support, that of page breaks. You 
can use page breaks to great effect, and if you expect your users to print your Web 
documents, there's really no reason not to use them. 

The next chapter takes a look at some of the Web development tools available. You'll 
learn about text editing tools as well as WYSIWYG tools. You'll also see how 
graphic-editing programs can influence your design decisions and improve your 
productivity. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Advanced Web 
Authoring 



In This Part 

Chapter 25 

JavaScript 

Chapter 26 

Dynamic HTML 

Chapter 27 

Dynamic HTML 
with CSS 

Chapter 28 

Introduction to 

Server-Side 

Scripting 

Chapter 29 

Introduction to 
Database-Driven 
Web Publishing 

Chapter 30 

Creating a 
Weblog 

Chapter 31 

Introduction to 
XML 

Chapter 32 

XML Processing 

and 

Implementations 



399 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 




400 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



JavaScript 



Up to this point, you have learned how to create static 
documents on the Web with HTML. However, as the Web 
matured from its meager beginnings, it was clear that static 
documents provided limitations — limitations that could be 
circumvented with a small level of automation. Enter scripting. 
Scripting is a simple form of programming usually used to refer 
to application macro languages, or in this case, to create small 
programs to help automate Web pages. This chapter begins 
the discussion of scripting by introducing the most popular 
scripting language on the Web, JavaScript. 



JavaScript Background 



Note 



JavaScript is the language of choice for the vast majority of 
scripting on the Web. It is supported by the two major 
browsers (Internet Explorer and Navigator), along with other 
varieties including StarOffice (www. staroffice. com) and 
Opera (www . opera . com). JavaScript is a relatively simple and 
powerful language, and is in broad enough use to make it the 
de facto standard for Web scripting languages. 

VBScript is an extension of Visual Basic created by 
Microsoft as a competitor to JavaScript. However, 
Microsoft's efforts were not as widely accepted, because 
JavaScript was introduced to the Web developer world 
first. As a result, Microsoft has added complete support 
for JavaScript (calling it Jscripf) to Internet Explorer, in 
addition to VBScript. 

However, using JavaScript does have a drawback. As long as 
there is more than one browser, there will be more than one 
way of doing things. Different developers keep up with 
industry standards and recommendations at different rates. 
The result is a mess for the lowly Web author who wants to do 
fun and exciting things with a Web page, but doesn't want to 
limit their site to only those with the latest and greatest 
browser. 

JavaScript is an object-oriented scripting language. With 
JavaScript, you can manipulate many variables and objects on 







♦ ♦ ♦ ♦ 
In This Chapter 

JavaScript Background 

Writing JavaScript Code 

Using JavaScript in HTML 
Documents 

Practical Examples 

♦ ♦ ♦ ♦ 







401 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



402 Part lv ♦ Advanced Web Authoring 



your page. With JavaScript and the Document Object Model (DOM), you can change 
the value of all the properties of all the objects on your page. Because the DOM 
requires browsers to redraw pages in response to events, JavaScript becomes far 
more powerful with the DOM. 

Note It's easy to confuse Java and JavaScript— after all, they appear to be closely 

related. Although JavaScript bases its syntax and structure on Java, the two 
languages are quite independent of each other and serve completely differ- 
ent purposes. Java is the product of Sun Microsystems, which created it as a 
cross-platform, object-oriented programming language. JavaScript is a product 
of Netscape, which developed it to enable Web developers to add programming 
functionality to Web pages. 

JavaScript is the most widely used scripting language on the Web. Originally 
developed by Netscape, JavaScript has now grown beyond the realm of anything 
Netscape can control and is supported natively by all the major browsers. In 
conjunction with the DOM, you can use JavaScript to animate, display, or hide any 
part of your page, validate forms, and interact in other ways with the end user. 

Note A standardized version of JavaScript is defined by the European Computer Man- 

ufacturers Association (ECMA, at www.ecma.ch), which calls their language 
ECMAScript. Netscape turned JavaScript over to ECMA in an attempt to stabi- 
lize the language and make it more widely accessible to other developers. This 
has not prevented Netscape or Microsoft from continuing to make their own 
innovations and changes outside the standards created by the ECMA. 

When combined with the DOM, you can do many things with JavaScript on a Web 
page, including the following: 

♦ Create a dynamic form displaying relevant fields, based on information already 
provided. For example, if a visitor answers yes to an insurance form question 
about whether any family members have died before age 55, a set of questions 
about which relatives and how they died would appear. If the answer is a no, 
the next question to appear might ask whether the visitor uses tobacco or 
illegal drugs. This helps to avoid such techniques as "If no, skip to question 13." 

♦ Reward certain screen interactions, such as answering a series of trivia questions 
correctly, by providing a congratulatory animation. The JavaScript can both 
evaluate the results of the quiz and animate a still image (or a series of images) 
without reloading the page and without requiring additional actions by the 
visitor, such as clicking a "see results" button. 

♦ Sort the results of a database table based on the sort order requested by the visitor 
without additional server requests. Once receiving the information from the 
server, the client can sort the data in useful ways utilizing JavaScript and the 
DOM. 

Note This chapter is a very brief introduction to JavaScript. For the full story, plus lots 

of examples and expert advice, check out Danny Goodman's JavaScript Bible 
(Wiley Publishing, Inc). The DOM is also covered in Chapter 26. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 403 



Even with all JavaScript can do, it has limitations. JavaScript is limited to its own 
sandbox within the browser. JavaScript cannot manipulate files on the client 
computer, including creating, writing, or deleting any system files. JavaScript also 
cannot execute any operations outside of the browser, including launching an 
installer or initiating a download. 

These limitations may seem like a handicap for developers, but they help to 
safeguard site visitors. Right now, few Web citizens fear JavaScript; because of its 
built-in limitations it is not perceived as a security threat. This is unlike Java and 
ActiveX. Many visitors have disabled the capability for their browsers to accept 
any of those technologies for fear of rogue programs. JavaScript would do well to 
avoid any similar security scare, so some modest limitations are an acceptable 
price. 



Writing JavaScript Code 

JavaScript follows a fairly basic syntax that can be outlined with a few simple rules: 

4- With few exceptions, code lines should end with a semicolon (;). Notable 
exceptions to the semicolon rule are lines that end in a block delimiter 
({or}). 

♦ Blocks of code (usually under controls structures such as functions, if 
statements, and so on) should be enclosed in braces ({ and }). 

♦ Although not necessary, explicit declaration of variables is a good idea. 

4- The use of functions to delimit code fragments is highly advised and increases 
the ability to execute those fragments independently from one another. 



Data types and variables 



Variables are storage containers where you can temporarily store values for later 
use. JavaScript, like most scripting languages, supports a wide range of variable 
types (integer, float, string, and so on) but incorporates very loose variable type 
checking. That means that JavaScript doesn't care too much about what you store in 
a variable or how you use the variable's value later in the script. 

JavaScript variable names are case-sensitive but can contain alphabetic or numeric 
characters. The following are all valid JavaScript variable names: 

Rose 
rose99 
total 
99_password 

Although JavaScript doesn't require that you declare variables before their use, 
declaring variables is a good programming habit to develop. To declare a variable in 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



404 Part lv ♦ Advanced Web Authoring 



JavaScript, you use the var keyword. For example, each of the following lines 
declares a variable: 

var name = "Hammond"; 

var total ; 

var tax_rate = .065; 

Variables are referenced in the script by their names — JavaScript doesn't require any 
characters to prefix the variable names. For example, you can reference the variable 
named total by simply using the following: 

total 



Calculations and operators 



JavaScript supports the usual range of operators for both arithmetic and string 
values. Tables 25-1 through 25-4 list the various operators supported by JavaScript. 





Table 25-1 
JavaScript Arithmetic Operators 


Operator 




Use 


+ 




Addition 


- 




Subtraction 


* 




Multiplication 


/ 




Division 


% 




Modulus (division remainder) 


++ 




Increment 


- 




Decrement 






Table 25-2 
JavaScript Assignment Operators 


Operator 




Use 


= 




Assignment 


+= 




Increment assignment 


- = 




Decrement assignment 


*= 




Multiplication assignment 


/= 




Division assignment 


%= 




Modulus assignment 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 405 





Table 25-3 
JavaScript Comparison Operators 


Operator 




Use 


== 




Is equal to 


i = 




Is not equal to 


> 




Is greater than 


< 




Is less than 


>= 




Is greater than or equal to 


<= 




Is less than or equal to 






Table 25-4 
Logical Operators 




Operator 




Use 


&& 




And 


II 




Or 


! Not 



Handling strings 



Strings are assigned using the standard assignment operator (=). You can 
concatenate two strings together using the concatenate operator (+). For example, at 
the end of this code, the full name variable will contain "Terri Moore": 



flrst_name = "Terri"; 
last_name = "Moore"; 
full_name = first_name + 



+ last_name; 



Control structures 

JavaScript supports the following control structures: 

♦ i f -el se 

♦ whi 1 e 

♦ for 



The if-else structure 

The if-else structure is used to conditionally execute lines of code, depending on 
a condition that is usually a comparison of values. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



406 Part IV ♦ Advanced Web Authoring 



The i f - e 1 s e structure has the following syntax: 

if ( condition ) 1 

... statements to execute if condition is true... 
) else { 

... statements to execute if condition is false... 
) 

Note The el se portion of the if el se structure is optional and can be omitted if 

you do not need to execute statements if the condition is false. 

For example, consider the following code: 

if ( state == "CO") 1 
flower = "Columbine"; 



This code sets the flower variable to "Columbine" if the state variable is "CO". (The 
State flower of Colorado is the Columbine.) 

The while structure 

The while structure is used to execute lines of code over and over again while a 
certain condition is true. 

The while structure has the following syntax: 

while ( condition ) 1 

...lines to execute while condition is true... 

} 

For example, consider the following code: 

while ( address. length < 20) 1 
address = address + " "; 



This structure will spacefill (add spaces to the end of) the address variable until it is 
20 characters in length. If it is already longer than 20 characters, the structure's 
statements will be skipped altogether. 

T 'P Always ensure that your whi 1 e structures include a means to change the struc- 

\ ture's condition to false. Otherwise, you run the risk of creating an endless loop, 
where the while structure's statements continuously repeat without end. 

The for structure 

The for structure is used to execute a block of code much like the while structure. 
The difference is that the for structure is tailored specifically for numerical loops, 
usually counting a specific number of loops. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 407 



The for structure has the following syntax: 



for (assi gnment; condition; change; ) { 
...statements to execute while condition is false. 



The assignment, condition, and change blocks of the for structure work together to 
control the number of times the statements are executed. 



♦ The assignment block's code is executed at the beginning of the loop and is 
executed only once. 

♦ The condition block provides a conditional statement. While this statement 
evaluates as true the loop continues to execute. 

4- The change block's code is executed at the end of each loop. 
Typically, the blocks reference the same variable, similar to this example: 

for ( x = 1; x <= 10; x++; ) { 

In this case, the loop's execution is as follows: 

♦ The variable x is set to 1 at the beginning of the loop. 

4- The value of variable x is checked — if it is less than or equal to 10, the loop's 
statements are executed. 

♦ At the end of each loop the variable x is incremented by one, and the loop is 
repeated. 

In short, this structure would execute 10 times. 

Note The description provided here for the for structure is somewhat simplistic. The 

various blocks (referenced herein as assignment, condition, and change) can be 
quite complex and take various forms. The simplistic explanation here shows 
the most common use as a numeric counter and loop handler. 

Break and continue 

Two additional loop-related commands come in handy when using loops in 
JavaScript: break and conti nue. 

The break command ends the loop, and code execution continues after the loop 
structure. 

The continue command ends the current iteration of the loop, and execution 
continues with the next iteration of the loop. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



408 Part lv ♦ Advanced Web Authoring 



Functions 

Functions are a means of grouping code fragments together into cohesive pieces. 
Typically, those pieces perform very specific tasks — receiving values to execute 
upon and returning values to indicate their success, failure, or result. 

There are essentially two types of functions, built-in JavaScript functions and 
user-defined functions. 



Built-in functions 

JavaScript has quite a few built-in functions to perform a variety of tasks. 
Augmenting the functions are a bunch of properties and methods that can be used 
with just about any object, from browser function to variable. 

The scope of built-in JavaScript functions, methods, and properties is too vast to 
adequately convey here. However, comprehensive references can be found on the 
Internet, including the following: 

♦ Netscape Devedge JavaScript 1.5 Guide 

(http://dev edge. netscape. com/1 i bra ry /manual s/2000/ 
javascri pt/1 . 5 /guide/) 

♦ DevGuru JavaScript Quick Reference 

(http : //www.devguru .com/Technologies/ecmascript/quickref/ 
javascri pt_i ntro . html) 



User-defined functions 

Like any other robust programming language, JavaScript allows for user-defined 
functions. User-defined functions allow you to better organize your code into 
discrete, reusable chunks. 

User-defined functions have the following syntax: 

function fundi on_name (arguments) { 
...code of function... 
retunn val ue_to_return; 



For example, the following function will spacefill any string passed to it to 25 
characters and return the new string: 

function spacefill (text) I 
while ( text. length < 25 ) 1 
text = text + " "; 

return text; 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 409 



Elsewhere in your code you can call a function similar to the following: 

address = spacefil 1 ( address ) ; 
This would cause the variable address to be spacefilled to 25 characters: 

♦ The s p a c efi 1 1 function is called with the current value of address. 

♦ The s p a c efi 1 1 function takes the value and assigns it to the local variable 

text. 

4- The local variable text is spacefilled to 25 characters. 

♦ The local variable text (now spacefilled) is returned from the function. 

♦ The original calling assignment statement assigns the returned value to the 
address variable. 

Note The arguments passed to a function can be of any type. If multiple arguments 

are passed to the function, separate them with commas in both the calling 
statement and function definition, as shown in the following examples: 

Calling statement: 

spacefil 1 ( address , 25 ) 
Function statement: 

function spacefill (text, spaces) 

Note that the number of arguments in the calling statement and in the function 
definition should match. 

The variables used by the function for the arguments and any other variables 
declared and used by the function are considered local variables— they are in- 
accessible to code outside the function and exist only while the function is 
executing. 



Using objects 



One of the most powerful uses of JavaScript is in accessing document objects. You 
can use this ability to check document attributes, change document contents, and 
more. 

Cross- A This chapter gives only a basic introduction to objects and the document object 
e erencej^ moc j e | p or mor e information on objects, the DOM, and how JavaScript relates 
to both, see Chapters 26 and 27. 

Most objects are accessed through the document's object collection. The collection 
is referenced through a structure of tiered objects whose structure is similar to the 
following: 

document. el ement_i n_document . sub -el ement_of_el ement 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



410 Part lv ♦ Advanced Web Authoring 



For example, the following statement references the address form field in the info 
form: 

document, info. address 

In order for this to work, the elements and subelements must be appropriately 
named in the document. For example, the form referenced in the preceding code 
would need name attributes for its elements: 

<form name="info" act i on="handl en . cgi " method="post"> 
<input type="text" name="addness"> 

To make use of objects, you also have to understand and use properties. Properties 
are attributes that an object has. In real life these would be attributes such as size, 
color, smell, and so on. In the DOM they are attributes such as value, length, and so 
on. 

You reference an object's properties by appending the property keyword to the 
object reference. For example, to reference the length of the address field, you would 
use the following: 

document, info.addness. length 



Event Handling in JavaScript 



You have seen the word events thrown around a lot in this part of the book so far. 
You'll remember that an event is any action taken by the visitor sitting at the 
browser. An event can also be caused by the browser, such as when the page finishes 
loading. Every mouse movement, every click of the mouse, every keystroke can 
generate an event. As a developer, you must decide what kinds of actions you want 
to take based on events. Acting on events requires event handlers, which are 
discussed later in this chapter. 

Table 25-5 shows the major scriptable events. 



Table 25-5 
Scriptable Events 



Event 



Trigger 



Load This event is triggered when the page is loaded 

Unload This event is triggered when the page is unloaded (usually when another 

page is called) 

MouseOver This event is triggered when the mouse goes over an object on the page 

MouseOut This event is triggered when the mouse is no longer over an object it was 

formerly over 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 411 



Event 



Trigger 



MouseDown This event is triggered when a visitor clicks (only the downstroke 
of the mouse button) on an object 

MouseUp This event is triggered when visitors release the mouse button 

they have depressed. Most systems handle only the mouseUp 
event, rather than both mouseDown and mouseUp, or only 
mouseDown. If visitors start to click (triggering a mouseDown), 
and then move the mouse off of the object (triggering a 
mouseOut), and then release the button (triggering a mouseUp), 
normally visitors don't want any action taken 

Click This event is triggered when visitors both click and release an 

object 

DblClick This event is rarely used in Web pages because Web pages rely on 

single clicks, but you can capture and act on a double-click, as well 

keyPress This event is triggered when a keyboard key is depressed and 

released 

keyDown This event is triggered when a keyboard key is depressed 

keyUp This event is triggered when a keyboard key is released 

Focus This event is triggered only in forms, when the cursor moves to 

highlight a field (either by tabbing to that field, by using a mouse 
to place the cursor at that field, or by using an access key to bring 
the focus to that field) 

Blur This event is triggered only in forms when the cursor is moved 

away from a field that was formerly in focus 

Submit This event is only triggered in forms when the object clicked is a 

BUTTON element with a type of "submit" or an INPUT element 
with a type of "submit" 

Reset This event is only triggered in forms when the object clicked is a 

BUTTON element with a type of "reset" or an i n put element with 
a type of "reset" 

Change This event is only triggered in forms when the contents of the 

object in focus are changed and then the focus leaves this object. 
In other words, if an input field has today's date in it and the 
visitor changes the date and tabs to another field or clicks 
another field, the change event is triggered 



For example, if you wanted a particular JavaScript function to execute after a page is 
loaded, you could use a <body > tag similar to the following: 



<body onload="javascript:runthis();"> 
This would execute the function r u n t h i s after the document loads. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



412 Part lv ♦ Advanced Web Authoring 



Using JavaScript in HTML Documents 

Incorporating JavaScript into your HTML documents is straightforward, and as 
you'd expect, handled through the use of the <scri pt> element. This section 
details the various methods of including JavaScript in your documents. 

Adding scripts with the script element 

Now that you have an idea what JavaScript can do, you must understand how to 
insert your JavaScript into your page. HTML offers the script element. If you want 
the script to be event-driven, include the sen' pt element in the head. If you want 
the script to execute when the page first loads, include the script in the body 
element. You can have both types of scripts. 

The basic syntax is the same as any other HTML: 

<script language="javascript"> 
/* script goes here * / 
</script> 

Most scripts tend to be placed directly in the Web page, but you have one other 
option. If your script is long or it uses functions you want other scripts to use, you 
can put your script into an external text file and link to it with the script element's 
s re attribute, as shown in the following code. For JavaScript scripts, the file 
extension is usually JS. 

<script language=" Java script" src="/javascript/li b_date . js"> 
/* Perhaps a comment what the external script is for */ 
</script> 

Although the most popular browsers (Navigator, Internet Explorer, Opera, and 
StarOf fice) are JavaScript-capable, other browsers still do not support it for a variety 
of reasons. As a responsible developer, you should hide your scripts from 
non-JavaScript browsers by commenting out the contents of your script. A browser 
ignores any tags it doesn't recognize, so the JavaScript-challenged browser will see 
the <scri pt> tag and ignore it; and then it will see a big, long comment (that 
actually contains your script) that it will ignore; and, finally, it will come to the 
</script> tag and ignore that. 

<script language="javascript"> 

<!-- Hide script from incompatible browsers 

...script here... 

// finish hiding script - - > 

</script> 

The JavaScript-capable browser, on the other hand, won't be fazed by HTML 
comments. It will ignore the opening HTML comment tag by accepted language 
convention and then process the rest of the contents as JavaScript. When it gets to 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 413 



the bottom, it sees a JavaScript comment marker (/ /) and ignores that line, which 
includes the closing half of the HTML comment tag. 



JavaScript execution 



When does JavaScript script execute? That depends on where the script is and how 
it's written. If a script has some effect on the initial display of the page, it should run 
before the page is loaded. If a script needs to be ready to run when a certain 
condition is met on the page, it needs to appear before the place on the page that 
will encounter the event. If a script needs to run in the course of loading the page, it 
needs to be included in the page itself. 

For example, consider the following code: 

<head> 

<script language="javascript"> 

function currentTime ( ) { 

van timeStr = ""; //declare an empty stning 

now = Time( ) ; 

timeStr = now. getHouns ( ) + ":"; 

timeStr = now. getMi nutes ( ) ; 

return timeStr; 
) 

</script> 

<title>My Home Page</title> 
</head> 
<body> 

<!-- nest of document here --> 
</body> 
</htmi> 

This snippet declares a function called currentTime in the document's head, but it 
doesn't execute yet. But, once the page is loaded, any hyperlink, form or other page 
feature that wants to use currentTime can, because it was declared before the page 
was loaded. If the script was placed at the bottom of the document, the entire page 
would have to load before the function became available, which could create 
problems if the user or page tries to invoke the function before it's ready. 



T 'P JavaScript is an interpreted language, which means it is evaluated and executed 

line by line. Because the JavaScript interpreter is moving through the scripts se- 
quentially, you need to make sure that functions and other routines are declared 
before they're needed. 



• 



The choice of when the script executes is yours. If you want the script to execute 
when the page is finished loading, you can place it last on the page, or put it in the 
document's head with a reference to it in the <body> tag, as follows: 



(BODY onload="JavaScm'pt:cunrentTime( )' 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



414 Part lv ♦ Advanced Web Authoring 



Your document can include as many scripts as you want or need in the head and 
body of the document, depending only on the patience of the end user to wait for the 
download. 



Practical Examples 



The uses for JavaScript are potentially unlimited. The following sections highlight a 
few of the more popular uses. 

Browser identification and conformance 

Using JavaScript you can determine what browser is being used to access your 
content and adjust the features of your documents accordingly. For example, you 
wouldn't want to use a JavaScript feature, such as wi ndow . focus ( ), with a browser 
that doesn't support the function. If you are using DHTML and the Document Object 
Model (DOM), it helps to know what browser is being used so you can determine the 
correct DOM model to utilize. 

Cross- . You can find more information on DHTML and the DOM in Chapters 26 and 27. 
Reference 




Typically, you can find the details of the browser in the navi gator. userAgent 
variable. For example, if someone is using Microsoft Internet Explorer version 6, this 
variable would contain something similar to the following: 

Mozilla/4.0 (compatible; MSI E 6.0; Windows NT 5.1; 
.NET CLR 1.0.3705; .NET CLR 1.1.4322) 

From the content of the variable, you can determine that the browser is Mozilla 4.0 
compatible and, specifically, is MSIE 6.0. This variable contains a lot of information, 
much of it superfluous to our intent — just knowing the browser. Additional variables 
exist to help ferret out the information without having to parse the navi gator 
. userAgent value. Some of these variables are listed in Table 25-6. 






Table 25-6 
Useful Browser Window Properties and Methods 

Variable Content 

navi gator. appNa me The formal name of the application (Microsoft Internet 

Explorer, for example) 

navi gator . appVersi on The version number of the browser 

navi gator . pi atf orm The operating system the browser is running on (Linux, 

Win32, etc) 

navi gator, user Language The language the browser is using (en-us, for example) 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 415 



Using i f /then statements, you can provide the appropriate code for various 
browsers, similar to the following: 

browser=navi gator. appName 
if (browser. indexOf( "Mi crosoft")! = -l) 
{ 

// Browser is MSIE, insert browser 

// browser specific code here 



if (browser. indexOf(" Netscape " ) ! = - 1 ) 
{ 
// Browser is vintage Netscape, insert 
// browser specific code here 



if (browser. indexOf("Moz ilia") !=-l ) 
{ 
// Browser is Mozilla, insert 
// browser specific code here 



However, this method is far from fool proof because the browser itself supplies this 
information — many browsers masquerade as other browsers and don't report their 
full details. A better way to write code is to detect actual features instead of relying 
on the browser name to ascertain which features it supports. 

You can tell if a function, method, or property exists by using an i f statement. For 
example, to determine that wi ndow . focus is supported by the user's browser you 
could use a construct similar to the following: 

if (window. focus) 
{ 

// window. focus() is supported, use it 
I 
el se 
{ 

// window.focus() is not supported, 
// use alternate method 



If you are using DHTML or otherwise making use of the DOM, you have probably 
noticed that different browsers implement the DOM differently. You can use the 
preceding method with document objects to determine the appropriate DOM model 
to use with code similar to the following: 

if ( document . get El ementByld ) { 

// access DOM via get El ementByld 



else if (document. all) 1 

// access DOM via document. all 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 



19:56 



416 Part lv ♦ Advanced Web Authoring 



else if ( document . 1 ayers ) { 

// access DOM via document . 1 ayers 



Note that you can determine if a browser supports DHTML at all by checking for any 
of the DOM models: 

if ( document . get El ementByl d || document . a 1 1 

|| document . 1 ayers ) 
{ 

// browser can do DHTML 



T 'P The Quirksmode Web site (www. qui rksmode.org) is an excellent source of 

browser compliance, quirks, and solutions. 



Last modification date 

Using the 1 astModifled property of the document object, you can place the 
timestamp of the current document file in your document's text. For example, the 
following code will insert the date (in the default format: MM/DD/YYYY HH:MM:SS) 
wherever the code is placed in the document: 

< s c r i p t > 

document. write(document.lastModified); 
</script> 



Caution The lastModified property is problematic when used with some browsers. 
Always test your code on target browsers before fully deploying it. 



Rollover images 



Using the DOM, JavaScript can dynamically change images in the current document. 
This technique is commonly used with graphical buttons — you create buttons that 
have a different look when the mouse passes over them and use the onMouseOver 
event to trigger a script to change the button accordingly. 

For example, suppose you created the two buttons shown in Figure 25-1. The button 
on the left is to be displayed when the mouse is not over the button, and the one on 
the right displays when the mouse is over the button. 

The document code to handle the rollover change is shown in the following 
listing: 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 417 



g btiiHoineNrm [„.Q(Sj'S 


g btnHonieHgh [1:1... Q(alS 


■ 














Horns 






Horns 


:;. : 












i 



Figure 25-1: Two buttons for rollover purposes— 
btnHomeNrm.jpg (left image) is the normal button, and 
btnHomeHgh . jpg (right image) is the highlighted button. 



;idoc 

"ht 

Chtml 

(head 

<ti 

<sc 

f 

/ 

/ 



TYPE HTML PUBLIC "-//W3C//DTD HTML 4. 01// EK 
tp : //www. w3.org/TR/html4/strict.dtd"> 



tle>Rollover Sampl e</ti tl e> 

ript type="text/ JavaScri pt"> 

unction btnHigh( btnName, hgh ) { 

/ Display conrect button - hgh = = normal button 

/ hgh = 1 = highlight button 

var obtn = document . get El ementByl d ( btnName ) ; 

if (hgh) { 

obtn.src = btnName + "Hgh. jpg"; 

I else 1 

obtn.src = btnName + "Nrm.jpg"; 



</script> 

;/head> 

;body> 

;img id="btnHome" src="btnHomeNrm. jpg" 
border="0" 

onMouseOver="JavaScript:btnHigh('btnHome',l);' 
onMouseOut="JavaScript:btnHigh( 'btnHome' ,0) ; "; 

;/body> 

;/html> 



This code works by using one function called by the OnMouseOverandonMouseOut 
events of the <i mg> element. When a user puts the mouse over the image, the 
function is called with the root name of the button (btnHome) and the highlight 
variable (hgh) set to 1 (highlight). The function gets the button's id via the name 
(note how the <i mg> element's id is the same as the root name of the images) and 
sets the element's s re property to the highlighted image. This process is repeated 
when the user removes the mouse from the element, but the highlight variable (hgh) 
is set to (do not highlight), and the function sets the element to the normal image. 

You can use the same function for an unlimited number of buttons as long as each 
uses a unique id and the same image file-naming conventions. 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



418 Part lv ♦ Advanced Web Authoring 



y 



T 'P To actually make the button do something, add an onCl ick event to the 

<img> tag to call another function, or directly manipulate the document 
. 1 ocati on . href property, as in the following examples: 

onCl i ck="JavaScri pt : dosomethi ngel se( ) " 

and 

onCl i ck=" document. locati on. href= 'home. html'" 



Caching images 



When animating images on a page, it helps to have the images (and all their variants) 
already cached by the browser. This eliminates the lag caused by the server sending 
the image(s) to the browser and the resulting delay in the image being displayed. 

To cache images, you can use a function similar to the following JavaScript function: 



function prel oadimages ( ) { 

var pictures = new Array 
/ List all the images to preload here 

"images/rdml . gi f " 
"images/rdm2 . gi f " 
"images/rdm3 . gi f " 
"images/rdm4 . gi f " 
"images/rdm5.gif" 
"images/rdm6 . gi f " 
"images/rdm7 . gi f " 
"images/rdm8. gi f " 
"images/rdm9 . gi f " 



// Load each image in array 

for ( i=0 ; i <prel oadimages . a rguments . 1 ength ; i++) { 
myi mages [i ]=new ImageO; 
my images [i].src=prel oadimages. arguments [i ] ; 



This function creates a new image object for each entry in the pictures array, 
causing the browser to request the image from the server and cache it locally. 
Thereafter, any request for the image will be served from the browser's cache 
instead of the server, eliminating display lag. 

To use this function, replace the images/rdm. . . entries with the correct URLs of 
the images you want to preload, and call the function from an on Loa d event within 
the document, as shown in the following example: 



;body onLoad=" Java Script: prel oadimages(); 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 419 



Note that preloading images takes just about as long as displaying the images 
normally. As such, little can be gained by preloading static images in the current 
document. However, images on subsequent pages, images used in animations, or 
dynamic buttons (see the previous section) are all good candidates for preloading. 



Form validation 



Form validation is one of the purposes most used by JavaScript. Consider the simple 
form shown in Figure 25-2. 



! Imp:' localhost Ch.iptei25 foimv.iliil.html - Miciosoft Internet Exploiei 



- | Q 



File Edit View Fiivorites Tools Help 



I 



o - © ■ a m 6 p i> * ® 0- & m -a 



Address ;bj hctp;//localhost/Chapcer25/forrrwalid,htrnl 



3H< 



*i 



Order Request 



Please enter details below. We will reply to your request within two business days. 



Quantity desired: 
(minimum 3) 



Zip code for estimating 
shipping cost: 

Email address: 



Submit 



*j Local intranet 



Figure 25-2: A simple form to request a quote for shipping products. 



Although the form is simple, a few pieces of information should be verified before 
the data is accepted: 

4- The quantity should be a number and be at least three. 

4- The ZIP code should be a five-digit number. 

4- The e-mail address should resemble a valid e-mail address (include an @ and a 
period). 

Performing complex checks on the data — such as validating that the ZIP code is 
authentic, not just five random numbers — isn't feasible using JavaScript. But the 
following document provides enough validity to weed out totally bogus data: 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd"> 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



420 Part lv ♦ Advanced Web Authoring 



(html) 
(head) 

<title></title> 

<script type=" text/Java Script") 

function req( my Field, my Label) ( 
// Check for non-blank field 
var resul t = true ; 
if (myFi el d . val ue == "") I 

al ert ( ' PI ease enter a value for the 

+ my Label +' " flel d . ' ) ; 
myField.focus(); 
resul t = false; 
} 
return result; 



function grThan (myField, myLabel , num) 
// Check if field value > num 
var resul t = true ; 
if (myFi el d . val ue <= num) I 

al ert ( ' PI ease enter a value for the 
+ myLabel +'" field, greater than ' 
+ val + ' . ' ) ; 
myFi eld. focus(); 
resul t = false; 
} 
return result; 



function islnt (myField, myLabel) { 
// Check if field is an integer 
var resul t = true ; 
if ( ! req (myFi el d , myLabel)) 

resul t = false; 
if (result) 1 

var num = pa rselnt (myFi el d . val ue , 10 ) ; 
if (isNaN(num)) { 

al ert ( ' PI ease enter valid number in the 

+ myLabel +' " flel d . ' ) ; 
myFi eld. focus( ) ; 
resul t = false; 



return result; 



function val i dEmai 1 (myFi el d , myLabel) { 
// Check for "valid" email (not empty, has 
// "@" sign and ".") 
var resul t = false; 
if ( req (myFi el d , myLabel)) 

resul t = t rue ; 
if (result) { 

var tempstr = new St ri ng (my Fi el d . va 1 ue ) ; 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 42 1 



var aindex = tempstr . i ndexOf ( "@" ) ; 
if (aindex > ) ( 

var pindex = tempstr . i ndexOf( ".", ai ndex) ; 
if ((pindex > aindex+1) && 
(tempstr . 1 ength > pindex+1)) { 

resul t = t rue ; 
) else i 

resul t = false; 



if ( [result) { 

a 1 ert ( "PI ease enter a valid email address " 

+ "in the form: yourname@yourdomain.com"); 
myField.focus( ) ; 



return resul t ; 



function valform (myform) { 
// Validate form fields as specified below 
// Quantity > 2 (and integer) 
if ( ! grThan (myform . qty, "Quanti ty" , 2 ) || 
! i slnt (myform . qty , "Quant i ty" ) ) { 
return false; 
) 

// Valid Zipcode 
if (! i si nt (myform. zi p , "Zi pcode" ) ) { 

return false; 
) 

// Valid emai 1 
if (! val i dEmai 1 (myform . ema i 1 , "Emai 1 ") ) I 

return false; 
) 
return true; 



</script> 
</head> 
<body> 

<hl>Order Request</hl> 

<p>Please enter details below. We will reply to 
your request within two business days.</p> 
<form name="orderf orm" 

action="http: //www. synergy -ent. com/pro jects/pi.php' 
method="POST" 
onSubmit=" return valform( document. orderform) ;"> 

<P> 

<table border="0" eel 1 paddi ng="5"> 

<tr><td> 

Quantity desired:<br> 

(minimum 3) 
</td><td> 

<input type="text" name="qty" value="3" 
si ze="4"> 
</td></tr> 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



422 Part lv ♦ Advanced Web Authoring 



<tr><td> 

Zipcode for estimati ng<bn> 

shipping cost: 
</td><td> 

<input type="text" name="zip" value="" 
size="5" maxl ength="5"> 
</td></tr> 
<tr><td> 

Email address: 
</td><td> 

<input type="text" name="emai 1 " value="" 
size="20" maxl ength="30"> 
</td></tr> 
<tr><td> 

&nbsp ; 
</td><td> 

<input type="submi t " val ue="Submi t"> 
</tdX/tr> 
</table> 
</p> 
</f orm> 

</body> 
</html> 

This code works by using the onSubmit event with the <form> element. When the 
user clicks the Submit button, the event handler calls the specified function 
(val form) before actually submitting the form data to the specified handler. If the 
function returns true, the form data is submitted. If the function returns f al se, the 
form data is not submitted and the user is returned to the document. 

The val form function steps through a handful of smaller functions to validate parts 
of the form. The various functions return true if the data is valid, f a 1 s e if the data 
is invalid. If all functions return true, the main function returns true as well, 
allowing submission of the data. If any function returns fa 1 se, the main function 
also returns fa 1 se, and the data is not submitted. 



Note 



Each validation function also displays an error message if invalid data is 
encountered, placing the user agent focus on the offending field. 

The functions used here are typical of functions used to validate most form data. 
However, each form is different and will probably require custom functions to 
validate its content— although you can use this example as a template, you 
should create tests specifically for your data. 

A comprehensive collection of form validation scripts can be found in the 
archives of Netscape's DevEdge site: 

http : / /developer. netscape. com/docs /examples/ Java script/ 
fonnval /overview, html 

Although the code was written in 1997, it still contains a wealth of useful func- 
tions for form validation. 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 423 



Specifying window size and location 

By accessing the user agent's properties you can manipulate some aspects of the 
user's browser window. Table 25-7 lists a handful of the useful properties available. 



Table 25-7 
Useful Browser Window Properties and Methods 



Property/Method 



Use 



Note 



window.moveTo(x,y) 

window.resizeTo(x,y) 
window.resizeBy(x,y) 

document.body.ciientWidth 
document.body.clientHeight 

document.body.scrollTop 



window.pageYOffset 
document.body.scrollLeft 

window.pageXOffset 



Move the upper-left corner of the browser window to 
position x,y on the user's screen 

Resize the browser window to x pixels wide by y pixels tall 

Resize the browser window, adding x pixels to the width 
and y pixels to the height (negative values shrink the 
window) 

Returns the current width of the browser window (in pixels) 

Returns the current height of the browser window (in 
pixels) 

Returns the number of pixels the user has scrolled down 
from the top of the document. Returns if the vertical 
scrollbar is inactive (Internet Explorer and compatible 
browsers) 

Returns the number of pixels the user has scrolled down 
from the top of the document. Returns if the vertical 
scrollbar is inactive (Netscape and compatible browsers) 

Returns the number of pixels the user has scrolled right, 
from the left edge of the document. Returns if the 
horizontal scrollbar is inactive (Internet Explorer and 
compatible browsers) 

Returns the number of pixels the user has scrolled right, 
from the left edge of the document. Returns if the 
horizontal scrollbar is inactive (Netscape and compatible 
browsers) 



The resize methods resize the entire window of the user agent, which includes 
toolbars, status bars, and so on— not just the content. Several other methods 
and properties can be used to return information about the browser and set 
certain attributes, but most of them are hit or miss as far as browser compliance 
is concerned. You can find more information on the properties and methods at 
DevGuru: 



www. devguru.com/Technologies/ecmascript/quickref/ 
javascript_index.htm: 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



424 Part lv ♦ Advanced Web Authoring 



You can use the code in the following example to play with some of the browser 
window properties and methods: 



;idoctyp 

"http 
<!-- Not 

(html) 
;head> 
<title 
< s c r i p 
f u n c t i 
// Res 
// at 
wind 
wi nd 



E HTML PUBLIC "-//W3C//DTD HTML 4.01 Transi ti onal //El\ 

: //www. w3.org/TR/html4/loose.dtd"> 

e the use of the transitional DTD above! --> 



>window Functions</title> 

t type="text/JavaScri pt"> 

on resetwindow() I 

et window to upper left of screen 

a size of 500 x 400 pixels 

ow.resizeTo(500,400) ; 

ow.moveTo (0,0); 



function si zeBy ( x ,y , smal 1 er ) 1 
// Increase or decrease (if smaller) 
// size of window by x and y pixels 
i f ( smal 1 er ) { 
x *= -1; 



y 



-1; 



window.resizeBy(x.y) ; 



function scrollreport() { 

// Report position of both scroll 

va r hpos , vpos ; 

var hmsg, vmsg; 

if ( navi gator . appName == 

"Microsoft Internet Explorer" 
hpos = document . body . scrol 1 Le 
vpos = document . body . scrol 1 To 

1 else 1 

hpos = window.pageXOffset; 
vpos = window.pageYOffset; 



ba rs 



) { 
ft; 



hmsg = "Horz Scroll: " + hpos; 
vmsg = "Vert Scroll: " + vpos; 
alert(hmsg + "\n" + vmsg); 



</h 

<bo 
<di 



cri 
d> 

on 
sty 
rm> 
<i n 
cce 
nCl 
<i n 
cce 
nCl 
sp; 



pt) 



Load="resetwindow( ) ;"> 
le="width: 600px; height: 600px; 

put type="button" val ue="Reset" 

ss key="R" 

ick="resetwindow( ) ;"></p> 

put type="button" val ue="Larger' ! 

ss key="L" 

ick="sizeBy(50,50,0) ;"> 

&nbsp ; 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 425 



Note 



input 

acce 
onCl 

3 >< i n 
acce 
onCl 

3 >< i n 
acce 
onCl 



type=" button" value="Smaller" 
sskey="S" 

ick="sizeBy(50,50,l);"X/p> 
put type="button" val ue="Scrol 1 Ba r Report'' 
sskey="B" 

ick="scrol 1 report( ) ;"></p> 
put type="button" value="Close Me" 
sskey="C" 
i ck="sel f. closet); "></p> 



C/di 

;/bo 
;/ht 



dy> 
ml) 



The <di v> sets a specified size for the elements in the document body to 
help ensure that scrollbars will appear at smaller window sizes. Note that the 
accesskey attributes for the buttons allow you to access the buttons even if 
you can't see them in the document window. 



Frames and frameset control 

You can also use JavaScript to help direct content to specific frames, if your 
document uses frames. 

The wi ndow . frames property can be used to access the frames currently active in 
the user agent window. You can access the frame properties using two methods, by 
name or by position in the frameset: 



Cfr 



</f 
// 
wi n 
// 
// 
wi n 



A frameset - -> 
ameset rows="25% , 50% , 25%"> 

frame name="f ramel" src="banner . html " /> 

frame name="f rame2" src="content . html " /; 

frame name="f rame3" src="f ooter . html " /> 

rameset) 

Access a frame (frame2) by name 

dow. frames ["frame2"].location=" home. html' 

Access a frame by position in frameset 

(first frame is 0, second frame is 1) 

dow. frames[l].location=" home. html" 



Either of the two preceding JavaScript examples will replace the content of f rame2 
with that of the home . html document. 



T 'P You can use the wi ndow . frames . 1 ength property to determine how many 

child frames are currently displayed in the active user agent window. 



Using cookies 



The Web is largely a stateless environment. The user agent requests a page and 
receives a response from the server. Typically, neither entity tracks the user's state 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



426 Part lv ♦ Advanced Web Authoring 



Note 



(beyond the client's concept of Back and Forward through the cache). Enter cookies, 
a way to save information on the user's machine that the user agent can later 
retrieve and use. 

Over the years, cookies have gotten a bad reputation. The technology is not at 
fault, but the use of it is. Several individuals and companies have used cookies 
to track user behavior and report the data for demographic, shopping, or simply 
spying purposes. The heart of the cookie technology is fairly benign and can be 
used for very useful purposes, such as remembering what messages you have 
read in a forum, favorite settings for sites, and so on. 



You can use the JavaScript document . cooki e property to set and retrieve cookies. 
The following code shows examples of functions to set, retrieve, and delete cookies: 



// setCookie 

// Sets cookie specified by 'name' (and optionally 
// 'path' and 'domain') to 'value'. 
// Cookie defaults to expire at end of sessio" 
// but can be specified to expire 'expires' 
// number of milliseconds from now. 
function setCooki e( name , value, expires, path 
if (expires) I 



domai n ) 



if (expires != 0) { 

Date( ) ; 



ICAp II ci : — uy i 

var curDate = new Date(); 

var expDate = new Date( curDate . getTime( ) + expires); 



var curCookie = name + "=" + escape( va 1 ue ) + 

((expires) ? "; expires=" + expDate : "") + 
( (path) ? "; path=" + path : "") + 
((domain) ? "; domain=" + domain : ""); 

document . cooki e = curCookie; 



// ge 

// Re 

// op 

// Re 

f unct 

var 

var 

var 

if 

b 

i 

1 e 



tCo 

tri 

ti o 

tur 

i on 

dc 

pr 

be 

(be 

egi 

f ( 

lse 

egi 



okie 

eves cookie value specified by 'name' (and 

nally 'path' and 'domain'). 

ns cookie value or null if cookie is not founc 

getCooki e( name ) 1 

= document . cooki e ; 
efix = name + "="; 
gin = dc . i ndexOf ( " ; " + prefix); 
gin == - 1 ) 1 
n = dc . i ndex0f( prefix ) ; 
begin 1= 0) return null; 

1 
n += 2; 



van end = document . cooki e . i ndex0f( ";" , begin); 

if (end == -1) end = dc. length; 

return unescape ( dc . substri ng( begi n + prefix . 1 ength , end)); 



P1:KTX 
WY022-25 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



Chapter 25 ♦ JavaScript 427 



// delCookie 

// Deletes cookie specified by 'name' (and 

// optionally 'path' and 'domain') by setting 

// expine to previous date. 

function del Cooki e ( name , path, domain) 1 
i f ( getCooki e( name ) ) { 

document . cooki e = name + "=" + 
( (path) ? "; path=" + path : "") + 
((domain) ? "; domain=" + domain : "") + 
"; expines=Thu, Ol-Jan-70 00:00:01 GMT"; 



Summary 



This chapter introduced you to JavaScript, a simple yet effective scripting language 
that can automate certain aspects of your documents. You learned what JavaScript 
is, the language's programming conventions, how to incorporate it into HTML, and 
were presented with several typical examples of its use. The next few chapters 
extend this knowledge, showing you the magic of Dynamic HTML. 



P1:KTX 

WY022-25 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:56 



428 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Dynamic HTML 



Dynamic HTML (DHTML) is a combination of standard 
HTML and CSS, and often JavaScript, used to create 
dynamic Web page effects. These can be animations, dynamic 
menus, text effects such as drop shadows, text that appears 
when a user rolls over an item, and other similar effects. 

This chapter introduces DHTML by reviewing some JavaScript 
basics and providing a look at the Document Object Model, 
which allows you access to HTML elements so that you can 
change their properties and/or content. Examples of common 
DHTML techniques are provided. 



The Need for DHTML 



DHTML, when used correctly, can significantly enhance the 
user experience. DHTML was originally best known for its 
flashy effects, and these still exist, but their importance is 
questionable, and when used improperly they can be annoying 
for your users. Fancy text animations and bouncing balls 
might be fun to write, but they're not so much fun for the user. 
This chapter focuses on the more practical aspects of DHTML. 
Most of these have to do with navigation. After all, your Web 
site is all about the user experience. Whenever you create an 
enhancement to your Web site, you should always ask, "Does 
this improve the user experience? Can they navigate my site 
more easily? Read my Web page more easily?" 



♦ ♦ ♦ ♦ 
In This Chapter 

The Need for DHTML 

How DHTML Works 

Document Object Model 

Cross-Browser 
Compatibility Issues 

Browser Detection 

DHTML Examples 

Breadcrumbs (Page 
Location Indicator) 
Rollovers 

Collapsible Menus 

♦ ♦ ♦ ♦ 



How DHTML Works 



DHTML can work either by applying certain CSS properties, or 
by using JavaScript to manipulate HTML elements. When using 
JavaScript, DHTML takes advantage of a browser's object 
model, which is a tree of objects based on the element set of 
HTML and on the property set of CSS. When you code against 
that object model, you can change an element's properties, 
which are associated with an element's attributes. An 
element's attributes, in fact, are referred to as properties in a 



429 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



430 Part lv ♦ Advanced Web Authoring 



JavaScript environment. How these properties are referred to, and what actions 
(methods) you can take on them, is determined by the Document Object Model 
(DOM). 



DHTML and the Document Object Model 

The DOM is a standardized process for accessing the parts of a Web page through a 
common application programming interface (API). What this means in practical 
terms is that each element in a document is accessible via script, usually JavaScript. 
We say "usually" JavaScript because no rule states that a language that accesses the 
DOM needs to be JavaScript. It can be any language, from Java (which is different 
than JavaScript) to C# or Visual Basic. As it turns out, though, most DOM-related 
activity vis-a-vis the browser is powered by JavaScript. 

The standardized form of JavaScript is called ECMAScript. This is a relevant fact 
because usually if you confine your scripting to a combination of the W3C's Level 
One Core DOM and ECMAScript, you'll be pretty successful at achieving 
cross-browser scripting compatibility. 

You can find the specification for ECMAScript at www. ecma- international .org/ 
publications/standards/Ecma-262.htm. 

The W3C's Level One Core DOM is basically a set of properties and methods that can 
be accessed from a given element. For example, one of the most ubiquitous (and 
dastardly, in many people's opinion) methods is the wi ndow . open ( ) method, which 
makes it possible for advertising pop-ups to appear. The open ( ) method acts upon 
the wi ndow object, which, although not an element (the DOM isn't restricted to 
elements), is still an object that can be manipulated by script. 



Using event handlers 

Notice the oncl i c k attribute in the following code fragment: 

oncl ick="this.style. fonts ize='60px'; this.style.color='red'"> 

This tells the browser that when the user clicks the di v element, something should 
happen. In this case, that something is that the following two attributes of the style 
element will change: 

♦ style.fontSize='60px' tells the browser to change the font size to 
60 pixels. 

♦ style.color='red'" tells the browser to change the color to red. 

The oncl i c k attribute is actually an event handler. An event is something that 
happens, as you probably already know. A party, for example, is an event. When a 
human triggers the on pa rty event, sometimes that human falls down drunk. When a 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 43 1 



human triggers an oncl i ck event in a browser, more benign things take place, such 
as text color changes, menu changes, and so on. Table 26-1 shows the common event 
handlers associated with JavaScript. 



Event Handler 



onAbort 
onBlur 



onChange 



Table 26-1 
JavaScript Event Handlers 



Usage 



Occurs when a user stops an image from loading 

Occurs when a user's mouse loses focus on an object. Focus is when 
the cursor is active on an object, such as a form input field. When a 
cursor is clicked within the field, it has focus, and when the mouse is 
taken out of the field, it loses focus, causing an onBl ur event 

Occurs when a change takes place in the state of an object, when, for 
example, a form field loses focus after a user changes some text 
within the field 



onClick 


Occurs when a user clicks an object 


onError 


Occurs when an error occurs in the JavaScript 


on Focus 


Occurs when a user's mouse enters a field with a mouse click 


on Load 


Occurs when an object, such as a page (as represented by the body 
element) is loaded into the browser 


onMouseOut 


Occurs when a mouse no longer hovers over an object 


onMouseOver 


Occurs when a mouse begins to hover over an object 


onSelect 


Occurs when a user selects text 


onSubmit 


Occurs when a form is submitted 


onLlnload 


Occurs when an object is unloaded 



When one of these events takes place, code is executed. Many browsers have their 
own, custom event handlers, but if you stick with those found in Table 26-1, you'll 
find cross-compatibility issues much easier to solve. 



It's all about objects 



The other thing you should have noticed about the JavaScript code fragment you saw 
at the beginning of this chapter is that there is some interesting dot syntax going on: 

style. fonts ize='60px' 

This is the key to all DHTML and working with the DOM. When script accesses an 
object, it does the same thing you need to do when finding objects on your 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



432 Part lv ♦ Advanced Web Authoring 



computer. When you look for a file on your hard drive, you drill down a group of 
nested folders to find something. So the final path might look something like this: 

C:\Documents and Settings\Chuck\Books\goodbook.doc 

On the World Wide Web, the same thing happens: 

http : //www. my website .com/2003/WORLD/i ndex.html 

Here, the Web server drills down a specific path that finds the document in bold. 
When you use JavaScript and the DOM you do the same basic thing. You begin with a 
top-level object, which is always the wi ndow object. Normally you don't need to 
name that, because it's understood to just always be there. Then, you drill down to 
the next level. The previous code which demonstrated how to use an o n c 1 i c k event 
(oncl i ck="thi s . styl e . f ontSi ze=' 60px ' ;) was able to circumvent this 
because the same object that called the event had changes (it changed itself), so we 
could use the this keyword. However, had another object been changed, you would 
have had to name that object's position within the hierarchy of document objects. 
The easiest way to do that is to be sure you use the i d attribute (which means the 
HTML object must contain an i d attribute containing a unique value), and then drill 
down to the object in your code. As shown in Figure 26-1, you can access most of the 
objects associated with a browser window using JavaScript and the DOM. 



Cross-Browser Compatibility Issues 

The most important caveat to exploring DHTML is that there are tons of 
compatibility issues. The newest iterations of Mozilla/Netscape and Internet 
Explorer have actually begun to come closer together, but developers working with 
DHTML during the height of the browser wars quickly learned that developing 
cross-browser DHTML was a very difficult proposition. As a result, most large 
professional sites eschew complex DHTML in favor of simpler cross-browser 
routines to improve navigation and other facets of the user experience, rather than 
excessive visual effects. 



Browser detection 

You can detect what kind of a browser a user is running by running a browser- 
detection script. This kind of script, along with some more finely tuned type of 
object detection described in the next section, is sometimes referred to as browser 
sniffing. At its simplest, a typical browser-detection script looks like this: 

< SCRIPT LANGUAGE="JavaScript"> 



var bName =navi gator . appName ; 

var bVer = parseFloat(navi gator. appVers ion); 

if (bName == "Netscape") 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 433 



defaultStatus • 


document ■ 




frames[i] > 




history ■ 


1 


location * 


t 


name « 


forv 


parent ■ 


i 


self ' 




status ' 


■ 










window * 


i L. 


clearTime out() i 




close() ' 




confirm() ' 




open() ' 


■ 


prompt() ' 




onload event() ' 


hash 


download ' 


host 


eventQ 


* hostname 




href 




pathname 




port 




protocol 




search 



length 

back() 

ird() 

go() 




hash 

host 

hostname 

href 

pathname 

port 

protocol 

search 

onClick event 

onMouseOver event 



action 

encoding 

length 

method 

target 

submitQ 

resetQ 

onSubmit event 

onReset event 



length c 
name* 

selectedlndex* 
value « 
type* 



area, password, hidden 



defaultValue ■ i 


form ' ' 


name ■ i 


value 1 1 


blur() ■ i 


focus i i 


select() ' i 


onReset event ■ > 


onSubmit event > > 



name • 

defaultSelected • 

Index • 

length • 

selected • 

selectedlndex • 

text • 

value • 



Figure 26-1: The Core Document Object Model used by ECMAScript (JavaScript). 

"Netscape Navigator" 



var browser 
el se 

var browser = bName; 
document .write( "You are currently using 
bVer, "."); 

// --> 
</SCRIPT> 



browser. 



Note 



When using simple browser-sniffing scripts, you can replace the code in bold 
in the preceding example with more complex tasks. In the next chapter, you'll 
see how to work with different CSS properties based on which browser a user 
is using. 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



434 Part lv ♦ Advanced Web Authoring 



Object detection 

Object detection is a more precise way of browser sniffing. It examines a browser's 
support for various aspects of the object model. This avoids the potential for 
successfully checking a browser version but not checking to see if a browser actually 
supports a specific object property or method. For this reason, object detection is 
the preferred method for browser sniffing and is considered best practice. In 
addition, unless you've got the object model of all the different browsers memorized, 
it's pretty hard to know which browser supports which object. It's easier to just 
check and see if a browser supports a specific object's properties or methods. 

The principles used in object detection are quite similar to those used in browser 
detection. You make use of JavaScript i f statements to check a browser's support 
for a named object's properties or methods. If it does support the object, you 
execute some given code. For example, using regular expressions can be very handy 
in JavaScript, but not if your users' browsers don't support them. So you create a 
simple detection script to see if they do: 

if ( wi ndow. RegExp ) I 

// execute some regular expressions 
I else { 

// provide an alternative to regular expressions 



DHTML Examples 



This section offers a few practical examples of DHTML. The scripts you'll see are 
necessarily simple to get you started. There are tons of resources on the Internet for 
additional help, including a vast array of freely available scripts that you can 
customize for your own use. We'll take a look at a few of the most popular DHTML 
routines. 



Breadcrumbs (page location indicator) 

If you've ever seen a series of links at the top of a browser window with the current 
page's link deactivated, you've seen breadcrumbs. Breadcrumbs derive their name 
from the concept of a navigation trail, designed to help users know where they are 
relative to the page they are in. Many user interface experts consider breadcrumbs 
an absolute necessity. Generally, you'll find breadcrumbs most easily managed 
through server-side scripting, but if you don't want to deal with server-side 
scripting, or, if you simply don't have access to a server-side scripting engine 
(maybe you are simply creating some pages on your home page offered by your ISP), 
you can create them using JavaScript. 

Writing out the code in pseudo-code 

Generally, the best way to develop any code is to spell it out in pseudo-code. In other 
words, think about what you're trying to do in English or whatever your spoken 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 435 



language is. In this case, our pseudo-code looks like this: 

Split the current URL into each folder. 
For each folder 

Create a link string-based object. 
Next Folder, 

Combine all result string objects together using a separator 
or delimiter to form a single string. 
Pnint the string out to the bnowser window. 

Using the window object to manage URLs 

As I mentioned, most action using JavaScript takes place by way of the DOM, which 
you'll see in action in the upcoming JavaScript breadcrumb example. In this case, 
you'll use the window 1 oca ti on property to handle the first part of your 
pseudo-code. The location property contains the current window's URL. You'll 
need this URL because in order to develop breadcrumbs according to the 
pseudo-code, you'll need to break apart the URL string and rip out each directory 
from it. You do this by separating each chunk of string that is delimited by a forward 
slash. 

Therefore, the first step in creating breadcrumbs is to initialize a JavaScript variable 
to store the URL, as in the following example: 

var sURL = wi ndow. 1 ocati on . toSt ri ng ( ) ; 



Building string arrays with the split() method 

Once you've got your URL string, you can use the JavaScript s pi i t ( ) method to 
store an array of substrings from the URL string you stored in the s U R L variable. The 
s p 1 i t ( ) method splits a string according to a delimiter you name as the method's 
argument. It stores each substring as part of an array, indexed in character 
sequence. This means you don't need to initialize an array with something like this: 

var sDi r = new Array ( ) ; 
Instead, you can initialize the array by using the s pi i t ( ) method: 

var sDi r=sURL . spl i t ( "/" ) ; 

Remembering that array indexes are counted beginning with 0, not 1, if your URL is 

http: //www.mydomai n. com/ my di rectory /here, the spl i t ( ) method used in 
the preceding code fragment will create an array that looks like this: 

sDir[0] = http: 
sDir[l] = www.mydomain.com 
sDir[2] = mydirectory 
sDir[3] = here 

Next, initialize a variable to store your output string: 

var sOutput=""; 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



436 Part IV ♦ Advanced Web Authoring 



Then, create a JavaScript for loop to loop through the array. Note that the loop 
looks a little different than some loops you may have seen: 

for (y=2 ;y< ( sDi r . 1 ength - 1 ) ;y++) 

What's different about this loop? Usually, you start such a loop with y=0 (or, 
more often, i=0, but i is simply the name of the new loop variable and we already are 
using that in another part of the code, as shown in Listing 26-1). Of course, in many 
instances you won't start a loop at an array's zero index value, and this is one of them, 
because you happen to know that the first two "splits" contain parts of the string 
related to the protocol (http:), and we don't want that or the first / of http://, either. 

Listing 26-1 : Building a Simple Breadcrumbs Header 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transi ti onal //EN" 

<html> 

<head> 

<script language="javascript"> 

function Nest(x) 

{ 

var x=x-3; 

var sNesting=""; 

for (i=0;i<x; i++) 

{ 

sNesti ng=sNesti ng + "../"; 

} 

return sNesting; 

function breadcrumbs ( ) 
{ 

var sDir = new Array(); 

var sURL = window.location.toStringt); 

sDir=sURL.spl it('7") ; 

var s0utput=""; 

for (y=2 ;y<( sDi r . 1 ength - 1 ) ;y++) 

{ 

s0utput=s0utput + " :: <a href='" + 
Nest( (sDi r . 1 ength -y)+l ) + "index. html ' >" + sDir[y] + "</a>"; 

) 

document. write(sOutput) ; 
I 

</script> 
<style type="text/css"> 



body 



font-family: Frutiger, Verdana, Arial, Helvetica, sans- 



serif; 
.breadcrumbs { 

font-size: lOpx; 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 437 



styl 
itle 
eta 

arse 
head 
ody> 
i v i 
crip 
eadc 
scri 
di v> 
i v s 
Opx; 
re i 
di v> 
body 
html 



Breadcrumbs</title> 
http-equiv=" Content -Type" content=" text/ html 
t=iso-8859-l"> 



d=" breadcrumbs" cl a ss=" breadcrumbs'' 
t language="javascript"> 
rumbs ( ) ; 
pt> 



tyl e="border : navy lpx solid; padding: 
text-align:center; margin-top:12px;"> 
s some content. 



12px; width: 



Listing 26-1 shows the breadcrumb code in its entirety. Note that it appends an 
i ndex . html to each directory (shown in bold in the listing), so you might have to 
change that to your directory's homepage. The final result is shown in Figure 26-2. 



i Breadcrumbs - MoziLU 



he Ldit View be boohrcicrki iools Window M2lp 
Eack For^a-d Reload 5top 




Figure 26-2: Breadcrumbs rendered in a browser using code from Listing 26-1 . 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



438 Part lv ♦ Advanced Web Authoring 



If you look at Figure 26-2, you can see there is one thing about the results you might 
not like. It would be better to have a "dry" breadcrumb containing a nonactive link 
for the page the user is currently on. Accomplishing that takes some JavaScript 
sleight of hand, but luckily, resources are already available for you to work with, as 
you'll see in the next section. 

Fine-tuning your breadcrumbs 

One example of an Internet-based resource you can rely on for creating breadcrumbs 
is a GNU-based JavaScript file that is freely downloadable over the Internet, including 
through this book's Web site. This is a much more finely tuned example of a 
breadcrumb script that accounts for a large number of variables. 

Note GNU is an open source licensing model that allows you to freely distribute and 

modify software, with some minor legal constraints, such as giving credit to the 
author of the software. You can view GNU licensing terms at www .gnu.org/ 
copyl ef t/gpl . html . 

The file was written by Henning Poerschke of WebMediaConception.com. The 
downloadable file is called j s_paths . j s. The JavaScript is well documented, but 

you can find more information about it at http: //webmedi aconception.com/de/ 
development/artikel /JS_breadcrumbs . en . html . 

You'll need to make one change in the JS file you download. You will want to wrap the 
entire script in a function named breadcrumbs, like this: 

function breadcrumbs ( ) 1 

//this is where the downloaded 
script should go 



In other words, you need to add the following line to the top of the script and a 
closing brace (}) to the end of the script: 

function breadcrumbs ( ) 1 

This turns the script into a function, which can then be called in the part of the page 
requiring the breadcrumbs. Listing 26-2 shows how to use it in your HTML. 



Listing 26-2: Using a Breadcrumbs JavaScript File 

<html> 

<head> 

<script 1 anguage="JavaScri pt" type="text/ ja vascri pt" src=" js_paths.js' 

</script> 

<title>Breadcrumbs</title> 

<meta http -equi v="Content -Type" content="text/html ; charset=i so-8859-1' 

<style type="text/css"> 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 439 



body 1 

font-family: Frutiger, Verdana, Arial, Helvetica, sans-serif; 
1 
.breadcrumbs 1 

font-size: lOpx; 



</style> 

</head> 

<body> 

<div i d="breadcrumbs" cl ass="breadcrumbs"> 

<script>breadcrumbs(X/scn'pt> 

< / d i v > 

<div styl e="border : navy lpx solid; padding: 12px; width: 440px; 
text-align:center; margin-top:12px;"> 
Here is some content. 

< / d i v > 
</body> 
</html> 



As you can see in Listing 26-2, using the JavaScript is as simple as inserting a link to it 
in the head element of your HTML and calling it on the part of the page you need the 
breadcrumbs to display. 

If you want to skip the step of giving the script a function name, you can simply 
import the script in the part of the page where you need the breadcrumbs to appear. 
Replace the bold script element in Listing 26-2 with this: 

<script type=" text/ javascript" src="/js_paths.js"X/script> 

If you choose this method, don't import the JS file in the head element. 

You might be wondering why to bother creating the breadcrumbs ( ) function at all. 
It appears to be more work. If your Web page uses a lot of JavaScript, it's a good idea 
to import all your JavaScript in the page header and call functions as needed, 
because it gives you a more modular design. This is truer when working with a lot of 
JavaScript code. If you aren't using much JavaScript, you should simply use 
whichever method is most comfortable to you. 



Rollovers 

You've probably seen image rollovers and may know how to code them. This section 
shows you how to create rollovers using CSS. First, you'll see how easy rollovers can 
be with CSS that requires no scripting using the a : hover pseudo-class. Then, you'll 
see how to manipulate CSS properties in rollovers using JavaScript. 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



440 Part lv ♦ Advanced Web Authoring 



Creating rollovers using the a:hover pseudo-class 

The easiest kind of rollover is to simply use CSS. You don't even need to use JavaScript. 
Instead, you can use the CSS a : hover pseudo-class to change the color or text size 
of an object. You can also change the background color or any other CSS property. 
This is all as simple as defining the a : hover pseudo-class within a stylesheet: 

<style type="text/css"> 

.button { 

font-family: Verdana, Arial, Helvetica, sans-serif; 

background -col or : #CCCCCC; 

padding: 3px; 

border: Ipx solid; 
} 
a : hover 1 

background -col or : #FF0000; 



</style> 

In the preceding code fragment, a button is defined in the .button class, and then a 
background -col or property is defined for the a : hover pseudo-class. Whenever 
the a : hover pseudo-class is used, the properties of its target take on whatever you 
defined for it as soon as the user's mouse "hovers" over the object. However, you're 
not quite finished. Can you figure out why that CSS alone will not create the rollover 
on the following HTML? 

<div><span cl ass=" button ">Rol loverK/spanXspan 
cl a ss=" button ">Rollover2</spanXspan 
cl a ss=" button ">Rollover3</spanX/div> 

The a : h o v e r pseudo-class works only on links, so you need to create a link for the 
desired effect to work. Listing 26-3 shows how to create the appropriate CSS and 
HTML to make the rollover effect work. 



Listing 26-3: Creating a Rollover Effect Using CSS 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 
Transit ional//EN"> 

<html> 

<head> 

<title>Using the a:hover pseudo-class</title> 

<meta http -equi v="Content -Type" content="text/html ; 

charset=i so -8859-1") 

<style type="text/css"> 

<!-- 

.button 1 

font-family: Verdana, Arial, Helvetica, sans-serif; 

background -col or : #CCCCCC; 

padding: 3px; 

border: Ipx solid; 

cursor : hand ; 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 441 



:hover 1 

background-color: # F F ; 
text-decoration: none; 



text-decoration:none; 



</style> 

</head> 

<body> 

<div><span cl ass="button" title="Go to Rollover Land"Xa 

href="#">Rolloverl</aX/span><span cl a ss=" button" ti tl e="Go 

to Rollover Land"Xa href="#">Rol 1 over2</aX/spanXspan 

cl ass="button" title="Go to Rollover Land"Xa 

href="#">Rollover3</aX/spanX/div> 

</body> 

</html> 



Note the link that is created for each button. Here, you simply assign a # identifier in 
lieu of a full link (but normally, of course, you'd insert a real URL). Note also that a 
text-decoration property is assigned to both the a element and the a-hover 
pseudo-class. This is done to avoid an underline being shown in the button. Finally, 
notice one additional bit of easy code that can make your links more dynamic. The 
ti tl e attribute is an underused HTML attribute that you can use on all HTML 
elements to add meaning to them. It's particularly useful on a elements. On browsers 
that support the title attribute, links are just that much more dynamic because 
when the mouse hovers over elements with title attribute values, a small "help" 
window, known as a ToolTip, appears, as shown in Figure 26-3. 



Using display properties with a:hover to create rollovers 

You can push the aforementioned concepts further by combining the a : hover with 
display properties to create genuine rollover effects. There is no JavaScript involved. 
They work because you can give an element a unique identifier through the i d 
attribute and take advantage of the different kinds of styling mechanisms available to 
anchor tags. First, you define a di v element to wrap around the a elements that 
serve as linked menu items, making sure to give the di v element a unique identifier: 

<div id="links"> 

<a href="http : //www. tumeri c . net/">Home<span> The Tumeric 

Partnership</spanX/a> 

<a 

href="http: //www. tumeric. net/ Service/Default.aspx">XSL<span> 

The TransTormati on Station is your one-stop source for gnarly 

XSL Transformations .</span></a> 

< / d i v > 

The first part of each link is displayed as a button. The second part of each link, 
contained in a span element, is the part that will appear below the menu item 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



442 Part lv ♦ Advanced Web Authoring 



¥fc Using the a:houer pseudo-class - Hozila 



Hie Edit View Gc Eooknarkf Tools Window Help 



11:32:25pm BEH3DB 



» ' * » • H «l | A Fifi://jr:/rVinimfiok°A?naod%?mfirrhns/'"hiirf:/Ronk<;/Wilfiy/rh;7 V ja^pairh 0j * » 
3ack Foward Reload : L-S£ il!_! £2 ! ! !i 1 |JB- nF J Prht 



^iJhotio HJ Bookmark? ^Release ^Jotes ^Plug-ins .^Extensions ^Support (~_jMozil a Ccmmuiity 



Rolloverl RDllover2 Rollcver3 



| Go l:o Rollcver Land | 



-£& O s£* fiD <*S ni3 :///;: /Documents and 5etangs£:hud^E5coksAM!ey/ch;7/a-hover.h(:-n# 



Figure 26-3: AToolTip as rendered in a browser when the title attribute is used on a link. 

dynamically when a user's mouse rolls over the button. This acts as a description of 
the link, and provides more information to the user. This is possible by declaring the 
following CSS rule for d i v elements with link id attribute values: 

d i v#l inks a span (display: none;) 

This tells the browser that no span elements contained within links that are 
themselves contained in di v elements with i tem id attributes should be displayed. 
The a : hover pseudo-class can then be used to display that same span element's 
content when a user's mouse is "hovering" over the link: 

d i v # 1 inks a:hoven span {display: block; 

position: absolute; top: 80px; left: 0; width: 125px; 

padding: 5px; margin: lOpx; z-index: 100; 

color: #AAAAAA; background: black; 

font: lOpx Verdana, sans-serif; text-align: center;! 



Change the value in bold in the preceding code to place exactly where you want your 
menu description to appear. You can download a running example of this from the 
downloadable code for this book. The file name is cssrol lover, htm. Eric Meyer 
developed this and other similar CSS techniques, and a similar file and many more 
can be found on his Web site at www.meyerweb .com/eric/css/edge/popups/ 
demo . html . 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 443 



Creating rollovers using JavaScript 

Creating rollovers using JavaScript can be as simple or as tedious as you wish it to 
be. Best practice would suggest that you should create rollovers, like any other 
JavaScript-based functionality, in a way that creates the least problems for the most 
users. 

To learn how to create good old-fashioned, image-based rollovers, see 
Reference 



Chapter 25. 



You can take advantage of the narrowing gap in differences among browsers by 
relying on the event models of IE5/6 and Mozilla (and by extension Netscape 7). For 
example, the following bit of code creates a rollover of sorts that results in a 
JavaScript alert box display when a user mouses over a portion of text: 

To use this rollover, <span styl e="col or : red ; cursor : hand ; " 
onMouseOver="al ert ( 'AMAZING !!!')"> 
mouse over these words</span> . 

The result of this simple bit of code is shown in Figure 26-4. 



Fiie Edit View Go Eooknarks Tools Window Help 



4 , £. „ a m 



.^ |<jfc: Fifi://jr:/rYnHimfinH°A?nflnri%?n^^^ v| | ^_qparrh | ^* 



To use this rollover, mouse over these words. 



/h 




Figure 26-4: When a user mouses over a portion of text, an alert box is displayed. 



Mozilla/Netscape 7 and IE5/6 allow all elements to use event handlers such as 
onmouseove r. But because it's an attribute, browsers that don't support event 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



444 Part lv ♦ Advanced Web Authoring 



handlers in all their elements will simply ignore the call to the JavaScript because 
they simply ignore the attribute itself. Keep this concept in mind when you're 
working with DHTML. In other words, try to limit the damage. The beauty of CSS is if 
you use it right, browsers that don't support CSS will simply ignore your styling, and 
the same is true for the use of event handlers in HTML. The same principle holds for 
CSS-based changes, even if you're using deprecated elements such as the font 
element (see Figure 26-5): 

<a HREF="http : //www. tumeri c . net/" styl e="text- 

decoration:none;"> 

<font color="#0000ff" 

onMouseOver="thi s . styl e . backgroundCol or = '#cccccc'" 
onMouseOut="thi s . styl e . backgroundCol or = '#ffffff'" 
title="Click Here!">The Tumeric Pa rtnershi p</f ont></a> 



File Edit View Gc Eooknarki Tools Window Help 



*• T » 



Forward Reload 5top 



| <& Fie://jr:/rnn imenhs%?nanH%?mehhhg<;/rhi id;/Rnnkq/Wiley/rh?ft V | jg^pflirh 



j^ w 



Doing business with The Tumeric liartnership 



-£& O \&* fiD <*S unknotf-ound: 'o" 



Figure 26-5: When a user mouses over a portion of text, the background color is changed. 



In the old days of browser wars and incompatibilities, these examples would only 
work in Internet Explorer, but now they'll work in Mozilla-based browsers, too. 



Note 



Saying that something works in Mozilla-based browsers means browsers based 
on the new open source Mozilla 1.0 codebase governed by the Mozilla Pub- 
lic License and Netscape Public License. Mozilla versioning can be confusing, 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 44 



because JavaScript tests for user agents will reveal (on a Windows machine) 
something like this: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.5) 
for browsers implementing the Mozilla 1 .0 codebase. This is because the Mozilla 
codebase was completely rewritten from scratch, and the old Navigator code- 
base was tossed into the ash heap forever. 



Collapsible menus 



Collapsible menus have become a staple in Web development, and you can generally 
avoid the hassle of creating your own from scratch by simply searching the Internet 
for something that is close to what you want; then make any adaptations necessary 
to reflect your own site's needs. Collapsible menus generally come in two styles: 

♦ Vertical menus that expand and collapse on the left side of a Web page and within 
a reasonably small space. When a user clicks his or her mouse on an item, a 
group of one or more subitems is displayed, and, generally, remains displayed 
until the user clicks the main item again, which then collapses the tree. 

♦ Horizontal menus that live at the top of a page. When a user rolls his or her 
mouse over an item, a group of one or more subitems is displayed, and, 
generally, disappears when the mouse loses focus on the item. 

How they work 

Generally, most collapsible menus rely on either the CSS display property or the 
CSS visibility property. The JavaScript used to manage these menus turns the 
visibility on or off depending on where a user's mouse is, or turns the display on or 
off to collapse or expand a menu. The difference between the vi s i bi 1 i ty property 
and the display property is that when you hide an element's visibility, the element 
still takes up visible space in the browser document. When you turn the di spl ay 
property off by giving it a none value (di spl ay="none"), the space where the 
affected element lives collapses. 

The other component to a DHTML menu is usually a JavaScript array containing all 
the menu items. For example, the JavaScript might contain a function for defining the 
menu's parameters: 

function i tem( pa rent , text, depth) I 
this. parent = parent 
this. text = text 
this. depth = depth 



When using a prewritten menu you acquire from the Internet, you'll generally want to 
look for a JavaScript array containing all the menu item parameters. In this case, the 
array would contain arguments for the previously defined function: 

outline = new makeArray(6) 

outline[0] = new item(true, 'SimplytheBest.net', 0) 

outlined] = new item(false, ' <A HREF="shareware . html ">Shareware & 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



446 Part IV ♦ Advanced Web Authoring 



Freeware</A>' , 1) 

outline[2] = new item(true, 'Scripts', 1) 

outline[3] = new item(false, ' <A HREF="Javascripts/dhtml_scri pts . html ">DHTML 

Scripts</A>' , 2) 

outline[4] = new item(false, ' <A HREF="cgi sen pts/cgi sen' pts . html ">CGI 

Scripts</A>', 2) 

outline[5] = new item(false, ' <A HREF="i nf o/i ndex. html ">Inf ormation 

library</A>', 1) 

To edit the menu for your own purposes, you simply change the links in the array 
(shown in bold in the preceding code). Most menus are built using an array that's at 
least somewhat similar to the preceding one. Note the correlation between the first 
argument in the item function (parent) and the actual values used in the array. 
When an item's parent argument is true, instead of a link, the category of links is 
named and no actual link is generated. When the parent argument is fa 1 se, a link is 
generated. Each menu you find on the Web might have a somewhat different 
implementation, but the general construction will be the same. 



Finding collapsible menus on the Internet 

As mentioned, you generally don't need to write your own menu from scratch, 
because so many developers have made them freely available. Instead, you can 
download someone else's menu and change the CSS and some of the other specifics, 
such as where the links go. 

One common style used with vertical menus is a Windows Explorer-like menu tree. A 
very good example of this kind of menu can be found at www. webreference, com/ 
programming/javascript/trees/Example/example.htm. 

You'll find an explanation of how the developer created these menus at www/ 
.webreference. c omprogra mm ing/javascript/trees/. 

A good resource for a wide variety of DHTML menus can be found at http : / / 
simplythebest.net/i nf o/dhtml_menu_scri pts . html . 

The scripts on this site contain detailed instructions on how to use the menus on 
your own site. You can enter "DHTML menus" into Google to find additional menus. 



Summary 



DHTML can be very complex, and some very long tomes have been written on the 
subject. This chapter introduced the following topics: 

♦ The Document Object Model (DOM) 

♦ Cross-browser compatibility issues and browser detection 

♦ DHTML examples such as breadcrumbs, rollovers, and collapsible menus 



P1:KTX 
WY022-26 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



Chapter 26 ♦ Dynamic HTML 447 



If you're not comfortable with scripting, you can find a wide variety of resources on 
the Internet for free scripts that you can adapt to your own needs with little 
JavaScript background. You also saw how you can avoid JavaScript altogether with 
some clever CSS manipulation. However, if you enjoy scripting or are already 
comfortable with it, you'll find that coding increasingly complex code against the 
Document Object Model will demonstrate that browsers can be software 
environments, and Web pages containers for very robust software applications. 



In the next chapter, you'll see how DHTML can work more specifically with CSS. You 
learn more about how the DOM is used to access CSS properties, and how to display 
effects with no scripting. 



P1:KTX 

WY022-26 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 23:55 



448 



P1:KTX 
WY022-27 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Dynamic HTML 
with CSS 



■ SS can be a powerful tool for creating dynamic pages 
^■0 with special effects. In this chapter, you'll see how you 
can change a CSS property dynamically in various browsers. 
You'll be introduced to Dynamic HTML, albeit briefly, as the 
next chapter serves as the real introduction to that concept. 
Here, you'll see how to access CSS properties and script them 
to perform tasks, such as change text colors. You'll see that 
every CSS property can be changed. 

You'll also find that some browsers, most notably Internet 
Explorer, feature CSS-like syntax for creating dynamic filtered 
effects such as drop shadows and blurs. 

Chapter 26 talked a lot about the Document Object Model 
(DOM) and objects, which can seem pretty daunting at first, 
so let's break it down to the simplest scale, that of CSS. Say you 
have a d i v element with a blue font inside it. To make the d i v 
(and its contents) accessible by script, you need to identify it 
somehow. You can do this using the i d attribute of the 
<di v> tag. The i d attribute is available to every HTML 
element for this very reason. So you can write a di v element 
like so: 

<div id="myID" styl e="col or : bl ue">I 'm blue now, but I may 
not be later. </div> 

Notice that since the example uses CSS, there's no need to use 
the font element to color our text. Now, say you want to 
change the text to red. This is easy with the DOM and 
JavaScript, especially if you're using Internet Explorer 4 or 
above, because IE makes accessing the DOM just a tad easier 
than some other browsers do: 

<div id="myID" styl e="col or : bl ue ; cursor:hand" 

oncl ick="this.style. fonts ize='60px'; this.style.colon='ned' 

I'm blue now, but I may not be later. </div> 

If you load the preceding code fragment into Internet Explorer, 
your browser will render as shown in Figure 27-1. 







♦ ♦ ♦ ♦ 

In This Chapter 

Dynamic HTML and the 
Document Object Model 

DHTML and CSS Properties 

Internet Explorer Filters 

♦ ♦ ♦ ♦ 



449 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



450 Part lv ♦ Advanced Web Authoring 





j File Edit View Favorites Tods Help 


J# 


I d - <0 - 1 


P * « « - & H - D ® 4 




: Arlrlre^ .^5] C : '.Documerts and Setting£\Chuck\Book\Wiey\th24',£tylechange.htm 


r|Qcn 



I'm blue now, but I nay not be Later. 



*j 



v. 



_i My Computer 



Figure 27-1 : When this text styled in CSS is clicked, it will change. 



Listing 27-1 shows some modification to the previous code fragment. This time, 
the this keyword isn't used because another di v object is created, along with 
an o n C 1 i c k event handler for that d i v object. When the new d i v object is 
clicked, the text in the d i v object labeled by the my I D attribute gets bigger and 
turns red. 

Note Listing 27-1 only works in IE4 and later and Mozilla/Netscape with Gecko 

engines (Netscape 7 and later). 



Listing 27-1 : Accessing an Element by Drilling Down 
the DOM Hierarchy 

<html> 

<head> 

<ti tl e>Setti ng CSS Properties Using Cross - Browser Scripting 

Routines</title> 

</head> 

<body> 

<d i v id="myID" styl e="col or : bl ue ; "> 

<p> I * m blue now, but I may not be later. </p> 




P1:KTX 
WY022-27 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 45 1 



< / d i v > 

<d 
#ccccc 

none" 
o n c 1 i c 
my I D . s 

</ 

</body 
</html 



iv styl e="wi dth : lOOpx; padding: 4px; background -col or : 

c; border: blue outset lpx; cursor:hand"> 

<div al i gn="center"Xa href="#" styl e="text -decorati on : 

title="Click to change font styles!" 

k="myID.style.fontSize='60px' ; 

tyle.color='red'">Click 

here</a> </div> 

div> 



Notice in Listing 27-1 the relationship between the my I D attribute and the code that 
is executed by the onclick event. Normally, you'll call a function from an o n c 1 i c k 
event. But you can also simply execute the script from the event handler, as well. 



You can see the changes in Figures 27-2 and 27-3. 



=T Setting CSS Properties Using Cross-Browser Scripting Routines - Microsoft Internet Explorer 



File Edit View Fcvorites Tools Help 



O'O'H a « p * * « 



a H - D ® * 



j Arrlre^K ^ C:\Docjments and Settings\Chuck\pooks\Wley\Ch24\L2401.htm 



■ H 



I'm blue now, but I may not be later. 
Click here 



m 



J My Computer 



Figure 27-2: This text can be changed by clicking the Click Here button. 



Cross- More detailed information about function calls and other intricacies of event 

Reference v nanc ||j n g can be found in Chapter 15, Scripts, and Chapter 26, DHTML. 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



452 Part lv ♦ Advanced Web Authoring 



™ Setting CSS Properties Using Cross-Browser Jcriptiie Routines - Microsoft Internet Explorer 



] File Edt View Favorites Tools He^j 



o - o - a e >& p*#e & - a n - □ m * 



; (ddress |gfile:l//C:/Cocuments%2Dand%205et:incs/ChuckyEools/WilerfOi2'/Li40:.htm# 



_ JGo 



I'm blue now, but I may not be 
later. 



-i 



i 



i My ■: 



Figure 27-3: When the button is clicked, the text changes. 



The solutions for changing CSS shown so far are of limited use because they rely on 
Gecko's and Internet Explorer's interpretation of the object model, the latter of 
which deviates quite substantially from that of the W3C object model. They both 
share the same core object model defined by the Document Object Model of the 
W3C. However, Internet Explorer expands on the DOM by a substantial amount. 



Note 



For the full list of properties and methods available to the Internet Explorer 
object model, visit http://msdn.microsoft.com/workshop/author/ 
dhtml/reference/dhtml- reference- entry, asp 



DHTML and CSS Properties 



What you've been seeing so far is that any object can be accessed using the Document 
Object Model, and one of those objects is the sty 1 e object (in Internet Explorer). 
Unfortunately, as easy as the scripts you've seen so far seem to be, the real world makes 
things a little harder, because different browsers use different nomenclatures for 
their objects. For example, Gecko (the engine running current versions of Netscape) 
calls its stylesheet object sheet. On the other hand, older versions of Netscape, 
such as 4.0, use this kind of document traversal to access style sheet properties: 



document. tags. p. fonts ize 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 453 



In order to account for all the differences in syntax between browsers, you need to 
set up browser sniffing routines which, as mentioned in the previous chapter, are 
chunks of code that check to see what kind of browser is accessing a Web page and 
executes the appropriate code. You'll see how this works in the next section. 



Setting CSS properties using JavaScript 

Navigator 4.x, Netscape 6, Mozilla, and Internet Explorer make CSS1 properties of 
elements accessible from JavaScript through their Document Object Model. 
However, the Navigator 4.x DOM and Internet Explorer DOM are different. They both 
implement parts of the W3C CSS1 standards, but they cover different areas, so 
JavaScript code that defines CSS1 rules on one browser won't work on other 
browsers. The Gecko layout engine covers all of the properties in W3C CSS1 
standards. 

To define CSS1 rules from JavaScript and have them work in Navigator 4.x, 
Netscape 6, Mozilla, and Internet Explorer, you need to do the following things: 

1. Insert an empty style element into the document's head and give it a unique ID 
through the use of the i d attribute. Then, later, you'll be able to change the 
properties of the style element. 

2. In the head element, place the JavaScript for defining your CSS1 rules in a 
script element so it executes before the body element is loaded into the 
browser window. This is to make Navigator 4.x play nice, because in Navigator 
4.z no "Dynamic CSS" will be rendered until you reload the page. 

3. Use a browser sniffing routine as shown in bold in Listing 27-2. Note that the 
key aspect of this routine is a series of "if" statements. If the browser is 
Netscape 4, do one thing, and if the browser is IE, do another. Notice also the 
use again of dot syntax to access the browser name through the use of the 
user Agent property of the navigator object to determine the browser name. 

On Navigator 4.x, the JavaScript is as follows: 

document. tags. P. fonts ize="25pt"; 
On Internet Explorer, the following is executed: 

document. styleSheets[" My ID"] .addRule ("P", " fonts ize:25pt") ; 

On user agents implementing Gecko, the following statement is executed: 

document . getEl ementBy Id (' tssxyz '). sheet . i nsertRul e( ' P @@ta { fontSize: 

25pt I', 

document. getElementById( 'tssxyz'). sheet. cssRules. length ) 

@@t a is evaluated. 

The final code should look something like Listing 27-2. 



P1:KTX 
WY022-27 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



454 Part lv ♦ Advanced Web Authoring 



Listing 27-2: Setting CSS Properties Using a Cross-Browser Script 



<<html> 

<head> 

<ti tl e>Setti ng CSS Properties Using Cross -Browser Scriptinc 

Routines</title> 

<STYLE ID="MyID" TYPE="text/css"> 

.MyClass { ) 

</STYLE> 



SCRIPT 


LANGUAGE="JavaScriptl 


.2"><! - 


- 


unction 


changelt ( ) { 








e w S i z e 


= 20; 








ar agt= 


navi gator . userAg 


ent . t 


oLowerC 


ase ( ) 


f ( (parselnt(navi gator 


. appV 


e r s i o n ) 


==4) 


(ag 


t . i ndexOf ( 'mozi 11a')! 


=-1) && 




a g t . i n d 


exOf ( ' spoof er ' ) = 


= -1) 






& (agt. 


i ndexOf ( ' compati 


Die') 


== -1) 


) { 


ocument 


. tags . HI . col or=" 


red"; 






ocument 


.tags. p. fonts ize 


=NewS 


ize; 




ocument 


.classes. MyCl ass 


.all . 


col or=" 


green 


ocument 


.classes. MyCl ass 


. p . CO 


1 or="bl 


ue" ; 



else if ( agt . i ndexOf (' gecko ' ) != -1) 1 
document. getElementById( ' My I D ' ) . sheet. insertRulet ' p 
@@t a { font-size: ' + NewSize + ' ) ' , 

document. getElementByld('MylD'). sheet. cssRules. length ) 

document. getElementById( ' My I D ' ) . sheet. insertRulet ' .MyClass 

@@t a { color: purple I', 

document. getElementByld('MylD'). sheet. cssRules. length ) 

document. getElementByldt 'My ID' ) . sheet. insertRulet 'p. My Class 

@@t a { color: blue 1', 

document. getElementByld('MylD'). sheet. cssRules. length ) 

else if ( ( parsel nt ( navi gator . appVersi on )>=4 ) && 

( agt . i ndexOf ( 'msi e ' ) 1= -1) ) { 
document . styl eSheets ["Myl D"] . addRul e ("p", "font-size:" 
@@ta + NewSize) ; 

document. styleSheets[" My ID "J.addRule (".My Class", 
@@t a "color:purple"); 

document. styleSheets[" My ID "J.addRule ("p.MyClass", 
@@ta "color:blue"); 



//--X/SCRIPT) 



</head> 

<body> 

<d i v styl e="wi dth : lOOpx; padding: 4px; background -col or : 

#cccccc; border: blue outset lpx; cursor : hand") 

<div al i gn="center"Xa href="#" styl e="text -decorati on : 
none" title="Click to change font styles!" 
onCl ick="changelt( ) ; " > C 1 ick 
here</a> </div> 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 455 



< / d i v > 

<p cl ass="MyCl ass"> 

Here is some test script in a P element 

</p> 

<div cl ass="MyCl ass"> 

Here is some test scnipt in a P element 

< / d i v > 
</body> 
</html> 



Listing 27-2 is a boilerplate of sorts. You could do a lot of different things that are 
relevant to specific browsers with it by replacing the code that gets executed 
between the braces in an i f statement, as shown in bold in the following example: 

if ( (parseInt(navigaton.appVersion)==4) & & 

(agt.indexOf ( 'mozi 1 1 a ' ) ! = - 1 ) && 
(agt.indexOf( 'spoofen' ) == - 1 ) 

&& ( agt . i ndexOf ( ' compati bl e ' ) == -1) ) { 
//do something here 

You can see in Figures 27-4 and 27-5 that clicking the Click Me button achieves the 
same kind of effects obtained through Listing 27-1, but this time the changes will 
work in most other browsers. 





j File Edit View Fcvorites Tools Help 


1 t 


1 - ■ @ <& P * « B - & ■ - D © 4 




; Arrlre^K |^ C:\Docjments and Settings\Chuck\pooks\Wley\Ch24\L2401.htm 


^Q f n 






Click here 



Here is some test script in aP element 
Here is some test script in aP element 



^jDone 



J My Computer 



Figure 27-4: This text can be changed in different browsers. 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



456 Part IV ♦ Advanced Web Authoring 



~r- Setting CSS Properties Using Cross-Browser Jcriptiie Routines - Microsoft Internet Explorer 



: File Edt View Favorites Tools He^ 



O O 



E 6 P * 



m - n © a 





address |Qffc:l//C:/Cocuments%2Dand%205etin(s/ChuckyEools/WilerfOi2'/Li40:.htm# 


v | gj Go 












Click here 








Here is somi 

lere is some :es 


test script in a P clement 

t script in s.P element 







J My C 



Figure 27-5: A cross-browser script lets the user change the text by clicking a button. 



Generally, CSS properties are all accessed the same way as shown in the two 
preceding examples. CSS properties in script tend to map out in such a way that if 
there is a hyphen in the property name, to access the property in script you delete 
the hyphen and upper case the next letter, like this: 

f o n t - s i z e 

becomes 

f o n t S i z e 

Therefore, you can perform tasks such as change visibility and create dynamic 
menus quite easily by manipulating CSS scripting properties. 



Cross- For examples of hierarchical dynamic menus and changing object visibility, refer 

Reference 



back to Chapter 26. 



Using behaviors to create DHTML effects 

Internet Explorer Behaviors, because they are accessed through style sheets, create 
the potential to completely avoid serious cross-browser incompatibility issues. 
When calling even highly complicated scripting routines, if you bind your routines to 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 457 



behavior selectors in style sheets, you might never need to worry about the 
ubiquitous JavaScript error codes that occur so often when users access your site 
with non-IE browsers. 

Behaviors can expose the XML object model as well as a number of other models 
and controls, including COM and ActiveX. Yet, because they're designed to be 
exposed through style sheets, browsers and operating systems that don't support 
COM won't throw a fit when you use them, because they'll be accessed only by 
browsers that support the controls you are calling. This is all possible without any 
direct referencing to the navigator object, the tried and true method of redirecting 
those you didn't want accessing certain pages. 

The syntax for a behavior looks like this: 

.my Behavior {behavior: url (value)) 

You may remember the syntax for other style sheet selectors that call on URLs to do 
their work, such as the background selector. The behavior selector operates on the 
same principle by binding a URL to the Web page, exposing the Web page to 
whatever methods and properties are residing in the URL source being referred to. 
Specifically, the bound source is a sen' ptl et (thus, the .set extension): 

.my Behavior {behavior: url(myScriptlet.sct)) 

Note A scriptlet is different than an imported JavaScript because it is specific to 

Microsoft browsers and is designed specifically to work with behaviors. 



If you are using an Active X or COM control, you would specify it as such: 

.myBehavior { behavi or : url (#my0bject ) I 
In this case, my b j e c t must be accessed in the HTML file by an < B J E C T > tag: 

<0BJECT ID=myObject ... X/OBJECTXUL) 

<D I V CLASS="myBehavior">my text, your text</DIV> 



Internet Explorer Filters 



IE includes a variety of dynamic effects in a browser-safe way that won't send 
browsers that don't support them crashing into a heap. The reason for this is that 
they use CSS-like syntax. If a browser doesn't support the syntax, the CSS code that 
implements a given effect is simply ignored. 

What follows is a closer examination of how to apply various visual effects through 
IE's extension to CSS2 style sheets. None of the properties that follow are part of the 
CSS2 specification — rather, they are extensions that are specific to Internet Explorer 
beginning with IE4 and, in the case of behaviors, IE5. 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



458 Part lv ♦ Advanced Web Authoring 



Filters 

If you've ever worked in a paint program you're familiar with filters and their effects. 
IE4 and IE have introduced them to the world of Web browsing through a set of 
controls that come packaged and install with the program. You can access them 
through style sheets, although not through CSS2 style sheets, but, instead, style 
sheet extensions that are compatible only with IE4 and IE. There are several kinds of 
filters, all of which fall into two basic categories: static and dynamic. 

Static filters are visual filters that create effects such as drop shadows, 
transparencies, and glows. These visual filters are called static not because they 
can't be made dynamic (they can through just a small amount of scripting code), but 
because their siblings, transition filters, are dynamic effects that create an effect 
during a transition of some kind, such as hiding or showing a layer, or the loading of 
a new page into the browser. In fact, the easiest kind of filter to create is a filter that 
produces an effect, such as a wipe or a fade, as a page loads. The code is simply 
plunked into a meta tag, and therefore cannot load an error message into browsers 
that don't support it. 

Like any other style sheet property, filters can be applied using event handlers. This 
can help committed developers who want to produce interesting projects for use 
over the Web. 

It's easy to determine if a particular HTML element can react to filter effects. 
Generally, if the HTML element is a windowless container, you'll be able to apply a 
filter to it. frame and i frame, then, are out, and di v and i mg are in. When using 
di v or span, it is imperative that you include at least one positioning property in its 
definition. In other words, in its style sheet, indicate either the height or width of the 
d i v or s p a n element, or its left and right position. 



Valid HTML filter elements 

The following list shows which elements you can apply filters to. 

♦ BODY 

♦ BUTTON 

♦ DIV (with a defined height, width, or absolute positioning) 

♦ IMG 

♦ INPUT 

♦ MARQUEE 

♦ SPAN (with a defined height, width, or absolute positioning) 

♦ TABLE 

♦ TD 

♦ TEXTAREA 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 459 



♦ TFOOT 

♦ TH 

♦ THEAD 

♦ TR 

The following section begins with a look at filters with the visual filters that are applied 
through style sheets, followed by a look at the light and visual transition filters. 



Visual filters 

There are several static filter controls that come as a part of the IE package, the 
definitions of which follow. They're easy to use with style sheet selectors, although 
the actual rendering of some is better than others. Some of them, such as glow, can 
be quite impressive, whereas the drop shadow effect may remind you of the 
infamous < B L I N K> tag. All visual filters follow the same general syntax: a CSS-like 
selector followed by a value consisting of the filter name and a series of its required 
parameters. 

{ filter: val ue ( parameter , parameter)) 

alpha 

You know what an alpha channel is, even if you think you don't. Any graphic file 
format that is capable of rendering a transparency or varying degrees of opacity has 
an alpha channel. In IE, the alpha channel sets the opacity level of an object. Using 
the optional startx(y) andfinishx(y) values allows you to create a gradient, as 
in the following syntax. 

{filter: a 1 pha ( Opaci ty=val ue , Fi ni shOpaci ty=val ue , Style=value, 
Sta rtX=va 1 ue , StartY=val ue , Fi ni shX=val ue , Fi ni shY=va 1 ue ) ) 

Valid parameter values are as follows: 

♦ to 100 for opacity, where is transparent and 100 is opaque 

♦ to 100 for the optional parameter FinishOpacity 

♦ A value of (uniform), 1 (linear), 2 (radial), or 3 (rectangular) for the style 
parameter, which sets the gradient shape 

♦ An x or y value for the StartX, StartY, FinishX, and Fi ni shY values. 

For example: 

HI {filter: alpha (20)) 

h!2 {filter: alpha (20, 100, 1. 10, 10, 200, 300)1 

As you might have surmised, you obviously would need to set all of the gradient 
values if you set the FinishOpacity value. 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



460 Part lv ♦ Advanced Web Authoring 



blur 

This filter creates a movement across the screen according to the parameters you 
set for it, and has the following syntax: 

1 filter: bl ur ( add=val ue , di recti on=val ue , st rength=val ue , )) 

Valid parameter values are as follows: 

♦ The boolean values true and false for add, which tell IE whether or not to add 
the original image to the blur 

4 A direction value of a point of a round path around the object (the value must 
be a multiple of 45 within a 360-degree path) 

4 A strength value that is represented by an integer, indicating the number of 
pixels affected by the blur (a default of 5) 

These parameters are represented in the following example: 

HI (filter: blur (false, 45, 20)1 

chroma 

This filter creates a transparency level out of a specific named color and has the 
following syntax: 

1 fil ter : chroma (color) 1 

No parameters are needed with this filter — the only needed value is the color, named 
as a hexadecimal color. This is not a reliable filter for any image that has been subject 
to dithering, either as a result of antialiasing, or a reduction in the size of its color 
palette from 24-bit to 8-bit, including JPEG, but is rather best used on an image that 
was created with a Web safe color palette in the first place, as in the following example: 

HI (filter: chroma (#ff3399)l 

dropShadow 

This filter creates a movement across the screen according to the parameters you 
set for it, and has the following syntax: 

(FILTER: dropShadow( Col or=val ue , OffX=value, OffY=value, 
Posi ti ve=val ue ) I 

Valid parameter values are as follows: 

4 Hexadecimal color values for color 

-4 A positive or negative integer for of f x and of f y, which indicates how many 
pixels along a horizontal (x) and vertical (y) axis the drop shadow is offset 

4 A zero or nonzero value for the parameter positive, which indicates whether or 
not to pick up transparent pixels for the drop shadow (0, false, is yes; any other 
number, true, is no, because the value is actually inquiring about 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 461 



nontransparent pixels, so if you want a drop shadow for a fully transparent 
object, you should set this value to 0.) 

Here is an example using some of the parameters: 

HI {filter: dropShadow (#336699, 8, 8)1 

Listing 27-3 shows how to build a drop shadow, and Figure 27-6 shows how it looks 
rendered in a browser. 



Listing 27-3: Building a Drop Shadow Filter 



Wl 

fil 

-e 
</ 
</ 
</ 



tml> 

ead> 

itle>Using a Drop Shadow</ti t 1 e 

head) 

ody> 

IV style 

dth:440p 

ter: dro 

re is a 

di v> 

body) 

html) 



= " font-si ze:50px; position: absolute; top: 20; 1 ef t : 1 5 ; 
x; height: 148; font-family: sans-serif; color: # F F 9 9 6 6 ; 
pShadow (#336699, 1, 1)"> 
drop shadow. 



File E'jif '■'■*■' F b ■:■[ if-rv T...>lv Hrl[- 



o o 



a ts lp ■&■ • 



& - & m - d © * 



; Address |ffi C ^Documents and Eetthg^ChjcWBook£\Mley\Ch24\L2403.hl:n 



* J Go 



j Lnks §S| LNN fij craigslst :£j Libs -£J Dictionary 45) dothet utorial ^J ti^N «J tree Hotrnai ^5] Google &] lib MLLH ag\ Jcvensirq 









i^Juone 



J m/ Lompute' 



Figure 27-6: A Drop Shadow rendered in a browser. 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



462 Part lv ♦ Advanced Web Authoring 



flipV 

This filter flips an object along a horizontal plane. It has the following syntax: 

i filter: flipV) 

This filter takes no parameters, as reflected in the following example: 

HI {filter: flipV) 

flipH 

This filter flips an object along a vertical plane. It has the following syntax: 

1 filter: flipH) 

This filter takes no parameters, as reflected in the following example: 

HI (filter: flipH] 

Glow 

This filter creates a glow around the outside pixels of an object. It has the following 
syntax: 

{FILTER: Gl ow( Col or=col or , Strergth=strength ) ) 

Valid parameter values are a hexadecimal number for the color value, and a value of 
1-255 for the strength value, which represents the intensity of the glow. The following 
example shows a strength value of 200: 

HI {filter: glow (#333399, 200) } 

gray 

This filter removes the color information from an object. It has the following syntax: 

{fil ter : gray I 
This filter takes no parameters, as reflected in the following example: 

HI {fil ter : gray I 

invert 

This filter reverses the values of an object's hue, saturation, and brightness. It has 
the following syntax: 

{filter: invert) 

This filter takes no parameters, as reflected in the following example: 

HI {filter: invert) 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 463 



light o 

The light filter can produce not only some fun effects, but can enhance a page 
visually, as well. The light filter has numerous methods you can call on for some 
special effects. The various methods you can call on are listed in the next sections. 

addAmbient 

The addAmbient filter adds an ambient light source to an object. When the light filter 
is first applied via a style sheet, a default addAmbient light method is applied that 
results in a black box. The syntax is as follows: 

object.filters. Light. add Am bient(R,G,B, strength) 

The parameters, in parentheses, must be in the order shown. 

addCone 

By naming a variety of values, you can position a cone light source to act as a kind of 
spotlight on a particular portion of an element or image. Here is the syntax for this 
filter method: 

object, filters. Light.addCone(xl,yl,zl,x2,y2,R,G,B, strength, spread) 

Valid cone parameters (in this order) include the following: 

4- xl is the light's starting point, or source position on the x axis 

♦ y2 is the light's starting point, or source position on the y axis 

♦ zl is the light's starting point, or source position on the z axis 
4- x2 is the light's target point, or target position on the x axis 

♦ y2 is the light's target point, or target position on the x axis 

Unlike many other filter calls, valid color ranges are defined as base-10 RGB ranges, 
rather than as hexadecimals. 

(0-255) Red 
(0-255) Green 
(0-255) Blue 

And in degrees: 

(0-255) Strength 
(0-90) Spread Angle 

You can only add a total of three cones to one image. In some versions of IE4, even if you 
only add three cones, if the user clicks a fourth time, an error message is generated. 

addPoint 

The addPoint filter adds a more finely focused area of light to an element than the 
addCone method. To use this method, follow this syntax: 

object. filters. Light.addPoint(x,y,z,R,G,B, strength) 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



464 Part lv ♦ Advanced Web Authoring 



changeColor 

The changeColor filter changes light color using the following syntax: 

object.filters. L i ght. changeColor(li ghtnumber, r,g,b, 
zero/nonzero ) 

1 i ghtnumber refers to the indexed number in the collection. Zero/nonzero refers to 
a nonzero or zero (0) number, with zero changing the color in an increment specified 
in the r, g, b parameters, and a nonzero number setting the color to the value 
indicated. 

changeStrength 

This filter changes light strength. To use it, follow the syntax shown here: 

object. filters. Light.changeStrength(l i ghtnumber, strength, 
zero/nonzero 

A zero/nonzero value of zero (0) results in an incremental or decremental change in 
strength value, and a value of nonzero results in a new strength set to the value 
indicated. 

Clear 

Clear deletes all the lights from the object, and has the following syntax. 

object. filters. Light. Clear 

moveLight 

Moves a light source to a position indicated in the method's parameters. The syntax 
looks like this: 

object .fil ters . Li ght .moveLi ght ( 1 i ghtnumber , x, y, z, boolean) 

boolean is a true/false operation, indicating whether the movement is absolute or 
relative to the source's original position. False means absolute; true means relative. 

mask 

Mask creates a stencil-like effect of an object by painting the object's transparent 
pixels and converting its nontransparent pixels into transparent ones. It has the 
following syntax: 

{Filter: mask( Col or=val ue ) 1 

Valid parameter value is a hexadecimal number for the color value; which indicates 
the color that the transparent areas should be painted, as shown in the following 
example: 



HI {filter: mask (#333399)] 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 465 



shadow 

This shadow filter creates a border around one of its edges to simulate a shadow. It 
has the following syntax: 

{ filter: shadow( col or=val ue , di recti on=val ue ) 1 

Valid parameter values are hexadecimal RGB values for color and a direction value of 
a point of a round path around the object (the value must be a multiple of 45 within a 
360-degree path). 

HI {filter: shadow(#333333 , 45)1 

wave 

The wave filter creates a sine wave across the vertical plane of an object. It has the 
following syntax: 

{ filter: wave( add=val ue , freq=value, 1 i ghtSt rength=va 1 ue , 
phase=value, strength=val ue , )} 

Valid parameter values are as follows: 

♦ The boolean values true and false for add tell IE whether or not to add the 
original image to the filter effect. 

♦ A frequency value is denoted by an integer that indicates the number of waves. 

4- A value ranging from 1-100 indicates the strength of the light being used in the 
filter. 

♦ A phase value between 1-100 indicates the offset percentage vis-a-vis the wave. 

♦ A strength value denotes the intensity of the wave represented as an integer. 

You can see these parameters in the following example: 

HI {filter: wave (false, 10, 45, 20, 50)1 

x-ray 

This filter reduces an image to a black and white format to resemble an x-ray. It has 
the following syntax: 

{ filter: Xray I 

This filter takes no parameters, as reflected in the following example: 

{filter: xray I 



Reveal transition filter 

This is a personal favorite of mine, mostly because I am inherently lazy, and, though 
not actually accessed by a style sheet, you can develop a nice page transition by 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



466 Part lv ♦ Advanced Web Authoring 



simply writing it in the meta tag at the beginning of a document. The revealtrans 
filter has the following syntax: 

(filter: reveal trans ( durati on=val ue , t ransi t i on=va 1 ue ) 1 

Possible values include a floating-point number as a duration value and an integer 
for the type of transition you want. There are several kinds of transitions an object or 
page can make as it reveals itself. These transitions are listed in Table 27-1. 





Table 27-1 
Possible Transitions 




Transition 






Value 


Box in 









Box out 






1 


Circle in 






2 


Circle out 






3 


Wipe up 






4 


Wipe down 






5 


Wipe right 






6 


Wipe left 






7 


Vertical blinds 






8 


Horizontal blinds 






9 


Checkerboard across 






10 


Checkerboard down 






11 


Random dissolve 






12 


Split vertical in 






13 


Split vertical out 






14 


Split horizontal in 






15 


Split horizontal out 






16 


Strips left down 






17 


Strips left up 






18 


Strips right down 






19 


Strips right up 






20 


Random bars horizontal 






21 


Random bars vertical 






22 


Random 






23 



P1:KTX 
WY022-27 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



Chapter 27 ♦ Dynamic HTML with CSS 467 



Two of the possible transition values are used in the following example: 

.filter {filter: reveal trans ( durati on=10 , t ransi ti on=22 ) 1 

This style sheet creates a transition that can be applied to whatever HTML element 
takes the class name "filter." You can also apply a transition page to a page as it is 
loaded or as it exits the page: 

<META HTTP-EQUIV=-'Page-Enter" 

C0NTENT= "Reveal Trans ( Durati on=5,Transition=2)"> 

Simply include this in your head tag along with any other meta tags you might have. 
Browsers that don't support the transition will simply ignore it. You can also write a 
transition that creates the effect as the browser unloads the page: 

<META HTTP-EQUIV="Page-Exit" 

C0NTENT= "Reveal Trans ( Durati on=5,Transition=2)"> 

In fact, it's been my experience that this tends to work better than the pages that 
have the Page-Enter attribute. 



Summary 



This chapter introduced you to using Dynamic HTML with CSS. You discovered that 
each CSS property is scriptable, and that you can even create dynamic effects 
without script. Specifically, this chapter covered the following topics: 

4- An introduction to the Document Object Model 

♦ DHTML and CSS properties 

♦ Internet Explorer filters 

So far, you've seen how client-side scripting, which depends on a browser's 
capabilities, can be used to take advantage of a browser's scripting support to make 
changes to Web pages on the fly. In the next chapter, you'll see how many developers 
remove this dependency by using server-side scripting, which allows you to create 
scripting routines on the server to dynamically produce HTML based on things such 
as user input or even user location. You'll see that when using server-side scripting, 
you can worry less about browser support because you generate basic HTML, and 
the "dynamic" qualities of Web page behavior are handled by the server. 



P1:KTX 

WY022-27 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:42 



468 



P1:KPE 
WY022-28 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



Introduction to 
Server- Side 
Scripting 



Earlier in this book, you learned the ins and outs 
of delivering fairly static data via HTML, CSS, and related 
technologies. Chapters 25-27 introduced you to client-side 
scripting and how it can be used to automate documents. 
However, client-side scripting is fairly limited in scope and 
resources. It cannot, for example, query a database and 
display unique content driven by the query. Enter the world of 
server-side scripting — higher level programs that can run on a 
Web server to extend its capabilities. This chapter introduces 
the server-side scripting concept and the most popular 
options for accomplishing server-side scripting. 



Note 



Due to the complexity of the server-side scripting sub- 
ject, it is outside the scope of this book to actually 
teach any server-side scripting. To do so would require 
several chapters for each different technology/language 
presented here. This chapter is only designed to intro- 
duce the concept and to give you the various options 
available for server-side scripts. 




♦ ♦ ♦ ♦ 
In This Chapter 

How Web Servers Work 

Market-Leading Web 
Servers 

The Need for Server-Side 
Scripting 

Server-Side Scripting 
Languages 






How Web Servers Work 



A Web sewer is a patient program that sits on your server (that 
is, the physical machine dedicated to serving pages and 
performing other server functions) waiting to receive an HTTP 
request via TCP/IP. 

Any server configured to handle communications via TCP/IP 
(the Internet's communications protocol) has ports. These 
aren't physical ports, like the serial port and parallel ports on 
the back of your computer, but they serve the same purpose. 
All HTTP requests come through port 80 unless the server has 




469 



P1:KPE 
WY022-28 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



470 Part lv ♦ Advanced Web Authoring 



been configured differently. Port 80 is the default Web server port. This is how your 
server, which may be a file server, an applications server, and an FTP server, in 
addition to being a Web server, keeps it all straight. 

When an HTTP request comes through port 80 to the Web server, the Web server 
finds the page requested, checks the permissions of the client making the request, 
and, if the client has the appropriate permission, serves the page. Figure 28-1 
illustrates the request process. 



HTTP 
request 

Returns page or 
- error message 



E^ 



^ 



[eh 



Mill 

Mill 



M 



Client computer 
running browser 



^ 



Server 



Figure 28-1 : The client requests the page. Then the server 
evaluates the request and serves the page or an error message. 



Generally, HTTP requests are anonymous. What this really means is an account has 
been created on the Web server for HTTP requests. When a request comes through 
port 80, it is assumed to come from this account. Each file on the Web server has 
certain permissions associated with it. If the HTTP account has adequate permission 
to read that page, and the page isn't otherwise protected, the Web server will serve 
that page. 

Server-side scripting fills many gaps and can be used for the following purposes: 

♦ "Intelligent" page generation. The contents of a page can be determined by 
the user — via previously established preferences, database queries, and 
so on. 

♦ Form verification and handling. In Chapter 23 you learned how JavaScript can 
be used to do basic form validation. However, using server-side scripts the 
form data can be validated at a much more detailed level — data verified against 
database content, run through credit card processors, and so on. 

♦ Dynamic page generation. Because most server-side scripting languages can 
interface with databases, generating dynamic content is fairly easy using 
server-side scripting. This concept is covered in more detail in Chapter 29. 

You can run server-side scripts via several different methods: 



♦ They can be run by specifying the script in a standard URL format, such as 

www. exampl e . com/dosomethi ng . cgi . 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 




Chapter 28 ♦ Introduction to Server-Side Scripting 



♦ They can be called from another script or static page by using a form action: 

<form action="val idate. cgi " method="P0ST"> 

♦ They can be called from another script or static page by using a link: 

The results of the survey can be found 
<a href="results.cgi">here</a>. 

In any case, the Web server must know how to handle server-side script 

requests — calling a CGI page (for example, validate. cgi) via any method will only 

cause an error in the server unless it knows how to process the request. 

In the case of most server-side scripts, the Web server simply turns over processing 
of the script to an interpreter or the operating system. The script is executed in a 
separate environment, able to draw upon other resources but still have its output 
sent to the HTTP client. 

Note The concept of using external resources to process scripts is covered in the 

Common Gateway Interface section later in this chapter. 



Market-Leading Web Servers 



Several different Web servers are in use today. Many of these servers are 
single-purpose applications, providing an HTTP interface into peripherals, 
applications, or appliances. 

In the mainstream HTTP server world, two programs reign supreme: The Apache 
Software Foundation's HTTP Server (Apache) and Microsoft's Internet Information 
Server (IIS). 



Apache 



The Apache Software Foundation is a group that provides support for the Apache 
community of Open Source projects. Included in those projects is the Foundation's 
HTTP Server Project (commonly referred to as Apache). Apache gets its name from 
the way it was originally developed. Originally, the server was made of several 
components or "patches," making it "a patchy server." 

Apache was one of the earliest developed Web servers and still undergoes continual 
development and improvement. Bug and security fixes take only days to find and 
correct, making Apache the most stable and secure Web server available. 

Another advantage of rapid development and releases is the robust feature set. New 
Internet technologies can be deployed in Apache much more quickly than in other 
Web servers. 

Apache continues to implement its features with distinct pieces, or modules. Utilizing 
a modular approach to feature implementation enables Apache to be deployed with 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



472 Part lv ♦ Advanced Web Authoring 



only the amount of overhead necessary for the features you want. It also facilitates 
third parties developing their own modules to support their own technologies. 

Apache supports almost all Internet Web technologies, including proprietary 
solutions such as Microsoft's FrontPage extensions. Apache supports all manner of 
HTTP protocols, scripting, authentication, and platform integration. 

Tip Visit the Apache module Web site (http : //modul es . apache . org) for in- 

formation on the modules included with Apache and the registered third-party 
' modules. 

Apache is available for many platforms, including Windows, UNIX, and Linux. It is 
estimated that more than 70% of Web servers on the Internet are Apache servers. 

IIS 

Microsoft's Internet Information Server is Microsoft's answer to serving HTTP 
content. Developed in early 1995, IIS was designed to provide HTTP deployed content 
on Microsoft NT servers. Although standard Web deployed documents (HTML, and 
so on) were part of the IIS design, the server was created to integrate more fully into 
Microsoft's server products — deploying a litany of Microsoft technology. 

IIS continues to evolve with each release of Microsoft's server platforms. A handful 
of new capabilities are included in the newest IIS versions, including the ability to act 
as sophisticated media servers, but the underlying structure is still HTTP deliverable 
content. 

Note Microsoft technologies offer a double-edged sword to the Internet. The Web 

owes a lot to Microsoft's development of both server and client technologies. 
However, some of the technologies come in proprietary packages unavailable 
to non-Microsoft platforms. For example, Active Server Pages (ASP) redefined 
interactivity on the Web, providing a near-Windows-like graphical user experi- 
ence. However, ASP technology is only available on Microsoft server platforms. 

Because IIS runs on Windows, controlling the server is accomplished through the 
use of standard Windows components and management consoles. However, as of 
this writing, IIS is still only available on Microsoft server platforms (NT/2000 
Server/2003 Server). 

The Need for Server-Side Scripting 

As you saw in Chapter 25, JavaScript and other client scripting languages are very 
limited in the amount of resources available to the script. As a general rule, 
client-side scripts can only access the user agent's features (usually a very limited 
set of the features) and the document's content. Although such capabilities are 
enough for simple automation and driving dynamic formatting, such limitations 
leave much to be desired. More robust content requires more robust tools. 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 




Chapter 28 ♦ Introduction to Server-Side Scripting 473 



Server-side scripts are so named because they run on the server instead of in the 
client's user agent. As such, server-side scripts can have access to all resources that 
the Web server and its underlying platform (operating system and hardware) have 
access to. Database content, hardware peripherals, robust data storage, and more 
are all available to server-side scripts. 

Most server scripting languages perform their magic in the background, without the 
user being aware that they are there. The Web server executes the script, which 
accesses databases, peripherals, or other servers, and passes any output from the 
script on to the user agent for display. 

For example, point your browser at an online shopping mecca such as Amazon.com. 
Several different server-side scripts are responsible for the content you see on every 
page. Some scripts provide the advertising banners, others provide the specials of 
the day, while others handle the searching and browsing requests. 

Server-side scripting offers another benefit that might not be readily apparent — the 
ability to communicate between user agents. Online Web-chat and other such 
services utilize server-side scripts and applications to accomplish their magic. 



Server-Side Scripting Languages 



Several different scripting languages are available for use on Web servers — more are 
appearing each day. This section describes the most popular languages and 
technologies in use today. 



Common Gateway Interface 



The Common Gateway Interface (CGI) was developed as a standard way for 
programs to talk to a Web server, thereby extending the server's capabilities. The 
CGI specification allows most programming languages to interact with Web servers. 
As long as a language can accomplish the following tasks, it is a viable CGI platform: 

♦ Read from standard input 
4- Write to standard output 

♦ Read from environment variables 

T 'P Just because a programming language can be used to implement CGI doesn't 

mean that it should be used. There are several security concerns relating to using 
CGI with a Web server. Many of the more common CGI-capable languages have 
built-in security components and therefore are safer to use. Other, unproven 
languages (operating system, macro languages, and so on) can present the 
outside world with more access to your server and underlying file system than 
you intend. 

The most common CGI languages are C and Perl. The former is a compiled language, 
that is, it needs to be converted to a binary program before it can be run. The latter 



v 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



474 Part lv ♦ Advanced Web Authoring 



is an interpreted language — interpreted languages are converted into binary 
programs on the fly, as they are run. 

Note Keep in mind that a program must output data in a form recognized by the 

user's interface, typically a Web browser. For example, a CGI program used to 
render an HTML document must pass the correct MIME type and document 
type definition as well as encapsulate its output in appropriate HTML tags. 

Each type of programming language (compiled/interpreted) has distinct advantages 
and disadvantages. Compiled languages tend to be faster executing, but require the 
extra compilation step to be deployed. Interpreted languages are a bit slower, but 
provide a little more flexibility during development. 

Note A great online resource for CGI scripting is the CGI Resource Index (www. cgi - 

resources . com). 

Several varieties of C are available for Windows and Linux platforms. Likewise, Perl is 
available for most platforms. 

ASP, .NET, and Microsoft's technologies 

As with most technologies, Microsoft has made several noteworthy achievements in 
creating tools and deployment solutions for the Internet. The latest initiative, .NET 
(pronounced dot-net), provides a solid platform to develop and deploy solutions 
over the Internet using Microsoft technology. 

Microsoft's earliest contributions to the Web were in the form of Active Server Pages 
(ASP) and ActiveX controls. ASP is Microsoft's answer to CGI, allowing their 
programming languages to be used to extend a Web server's capabilities. ActiveX 
controls extended the interactivity possible in Web pages by providing standard, 
Windows-like controls for users to interact with data on the Web. An example of a 
complex ActiveX control is provided in Figure 28-2, which shows the interface for a 
popular network camera. 

Note ActiveX controls only loosely fit into the scheme of server-side scripting, because 

they are actually downloaded and used by the client instead of the server. They 
are mentioned here for a sense of completeness and because they provide a 
viable option for extending the capabilities of the Web. 

For the most part, ASP operates much like standard CGI, incorporating programs to 
extend a server's capabilities. For example, the following code uses Visual Basic to 
store a value that is later output within an HTML document: 

<X@ Page Language="VB" %> 

<% 

Hel 1 oWorl d . I nnerText = "Hello World!" 



< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EK 
"http://www.w3.org/TR/html4/strict.dtd"> 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



Chapter 28 ♦ Introduction to Server-Side Scripting 475 



&rver Web Client - W*h Paye Dialog 



a 



%na 



%[%!* 




H3lp I About 



I nnaNnnr £vialnn r;£M 
Fl'^ire Ra:e: 10 fps 







Figure 28-2: The ActiveX control used by a popular network camera to allow control of 
the camera over the Internet. 

<html> 

<head> 

<title>Hello World ASP Sampl e</ti t 1 e> 

</head> 

<body> 



<p i d="Hel 1 oWorl d" runat="server"X/p> 

</body> 
</html> 

This simple example only scratches the surface of the power behind ASP. More 
complex code could look up data in a database and present it in tabular format or 
perform other complex operations whose results could then be presented in HTML, 
using the same method as shown previously. 

To use ASP (and the latest ASP.NET) requires a Microsoft Server running IIS along 
with the various pieces of ASP and .NET technologies. A good tutorial for getting up 
and running with ASP appears on the ASP101.com Web site, at www . asplOl . com/ 
1 essons/i nstal 1 .asp. 

Note The ASP101 Web site is a great resource for all things ASP-related— tutorials, 

sample code, and more (www. asplOl . com). 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



476 Part lv ♦ Advanced Web Authoring 



PHP 

PHP is a relative newcomer to the server-side scripting arena. However, it is one of 
the few solutions that were developed specifically for Web automation. As such, it 
has the most robust set of features for presenting all kinds of data in Web-friendly 
formats. 

Hypertext Preprocessor (PHP for short) is essentially a general-purpose scripting 
language with the following features: 

4 Based on open source technologies 

♦ The capability to run before the resulting page is displayed 

♦ A Perl-like structure and syntax 

4 Robust HTTP handling capabilities 

4- The capability to coexist with raw HTML in the same file 

4 Modules for interacting with other technologies, such as MySQL 

Unfortunately, PHP also has some serious drawbacks, also relating to its newness 
and genesis as a Web programming language: 

4 Numerous security issues (although they are typically found and fixed quickly) 
are compounded by the relative accessibility of the language to fledgling 
programmers. 

4 PHP versions up through 4.3 do not have robust object handling capabilities. 
As such, the language is not as flexible (or, arguably, as powerful) as those 
languages that do have robust object-oriented programming (OOP) structures. 

4 The structure of PHP programs can be fairly loose, allowing bad programming 
techniques to be used where highly structured code would otherwise be used. 
(Note that this is also a benefit as PHP tends to be easy to learn and the 
concern is mitigated if the person learning PHP takes the time to learn good 
programming habits as well.) 

The following code is an example of how PHP could be used to render the "Hello 
World" example shown in the ASP section, earlier in this chapter: 

<?php 

$HelloWorld = "Hello World!"; 

header( 'Content-type: text/html ' ) ; 
pnint <<<HTML 

< 1 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/stnict.dtd"> 

<html> 

<head> 

<title>Hello World ASP Sampl e</ti tl e> 

</head> 

<body> 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 




Chapter 28 ♦ Introduction to Server-Side Scripting 477 



<p>$HelloWorld</p> 

</body> 
</html> 
HTML; 
?> 

As with the earlier ASP example, this simple PHP example only scratches the surface of 
what you can accomplish with PHP. Instead of simply setting a string variable, the code 
could access a database and present the resulting data in a number of complex forms. 

PHP is available on Windows and Linux and requires that the PHP processor be 
installed on the Web server (both operating system and Web server application). 

Note You can find several sources of information online for PHP. The best resource 

is the PHP Web site itself (www . php . net), which has full language documen- 
tation, sample code, and more. For more sample code, visit the PHP Resource 
Index, at http://php. resource index. com. 



ColdFusion 

ColdFusion by Allaire (now owned by Macromedia) is one product that greatly 
increases what your Web site can do without requiring any programming. Using a 
simple language, called Cold Fusion Markup Language(CFML), you can create 
powerful scripts you write right into your HTML pages. The ColdFusion server 
returns the script's results right into your page. 

Some of the cool things you can do are as follows: 

♦ Schedule the generation of a page daily hourly, or at whatever interval you 
choose. 

♦ Pull content off other sites and parse it into your own format. (Get permission 
from the site owner before you try this.) 

♦ Send mail to everyone in a database from a Web page based on criteria 
indicated on the form on the Web page. 

♦ Insert records into a database. Update a database record. Read a database for 
records that meet certain criteria. 

ColdFusion is available for both NT and UNIX (Solaris) platforms. It works with 
ODBC-compliant databases. You can find out more from the Macromedia Web site 

(www.macromedi a . com). 



Summary 



Web publishing has come a long way from its humble beginnings as a means of 
delivering static textual documents. Using various scripting technologies, browser 



P1:KPE 

WY022-28 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 20:3 



478 Part lv ♦ Advanced Web Authoring 



plug-ins, and other technologies, you can deliver just about any type of content via 
the Web. 



In this chapter, you learned how server-side scripting can be used to extend the 
capabilities of the Web server, tying in almost any resource available to the server, 
including databases, peripherals, and more. 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Introduction to 
Database-Driven 
Web Publishing 



Although databases are not new to the computer world, 
only in the last few years has database-driven Web 
content become widespread. From real-time inventory 
tracking to dynamic content publishing (think online 
newsletters, and so on) database integration can add a lot of 
power to your online documents. This chapter introduces you 
to the concept of database-driven publishing. 



Note 



A full discussion and in-depth examples of database pub- 
lishing are beyond the scope of this book. This chap- 
ter introduces you to the concepts and should give you 
enough information to get started. However, for more 
information on the subject you should pick up a book 
dedicated to the subject. 




♦ ♦ ♦ ♦ 

In This Chapter 

Understanding the Need 
for Database Publishing 

How Database Integration 
Works 

Options for Database 
Publishing 

Database Publishing Case 
Study — A Newsletter 

Authentication and Security 

♦ ♦ ♦ ♦ 



Understanding the Need for 
Database Publishing 

As previously discussed throughout this book, pure HTML 
documents tend to be very static, offering little to no dynamic 
content. Consider the following examples: 

♦ An order form presented with straight HTML cannot properly 
represent the vendor's stock levels, potentially allowing 
customers to order more product than can be shipped. 

♦ An online newsletter must be manually assembled and edited 
in HTML. Furthermore, such online content cannot be easily 
searched or presented in multiple formats. 

♦ Customer records, historical data, and so on cannot be 
manipulated, searched, or validated against other data. 



479 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



480 Part lv ♦ Advanced Web Authoring 



However, when your documents can interact with database content, you can easily 
mitigate the concerns mentioned in the preceding list: 

♦ The order form can represent the current stock level, alerting customers to 
backordered items and potential ship dates. The form can also look up 
shipping estimates and tax rates where applicable. 

♦ The online newsletter can be edited piecemeal and assembled by running 
database queries against a database holding massive amounts of content. The 
content (even historical content) can be represented in many forms and 
searched for specific content. 

♦ Data can be stored, retrieved, validated, and otherwise manipulated. 

How Database Integration Works 

HTML and client-side scripts are not equipped to access databases. Database access 
requires tools on the server side of the equation, typically server-side scripts or an 
HTTP-enabled data server. 

Figure 29-1 shows a simple example of how standard HTTP requests (typically HTML 
documents) are served. 




Figure 29-1 : A typical HTTP request is served 
by the Web server. 

Figure 29-2 shows an example of how a Web server can be integrated with a database 
using server-side scripting. 

Cross- A For more information on server-side scripting, refer to Chapter 28. 
Reference 



Options for Database Publishing 

Two methods are commonly used for database publishing: pre-generated content 
and on-demand content. Each method has its advantages and disadvantages, as 
discussed in the following sections. 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 4- Introduction to Database-Driven Web Publishing 481 



User 
Agent 



Web 
Server 



Server-side 
Script 




Database 



Figure 29-2: A server-side script can be relied upon to store and 
retrieve data from a database. The same script can manipulate the 
data in many ways before passing it back to the server for delivery 
to the requesting client. 

Pre-generated content 

The concept of pre-generated content relies upon background scripts being run on 
the server at regular intervals, generating static pages from the database content. 
For example, a script might run every few hours to refresh the content, allowing 
recent articles or prices to appear on the appropriate pages. 

Pre-generated content is typically used on sites that experience a high volume of 
traffic, or where the content doesn't change much. 

The advantage to pre-generating content is that it takes the load off of the database 
server, letting the Web server do what it does best, serve static HTML pages. The 
disadvantages are that the content isn't as timely (it's only as up-to-date as the 
frequency of the generating script allows it to be), and the user cannot dynamically 
generate the content. 



On-demand content 



On-demand content relies on server-side scripts to deliver the data each time a user 
visits a page. The scripts query the database for appropriate content and display it 
as required on each page. For example, a "Recent Headlines" script might run at the 
top of the main page, displaying the headlines of the most recent articles. 

On-demand content is typically used on sites that experience a lower volume of 
traffic or on sites where the content changes rapidly or must be accurate 
up-to-the-minute. 

The advantage to on-demand content is that it can be as current as the data in the 
database allows. The requesting scripts can also dynamically generate the content, 
allowing a user more control over what he or she sees. The disadvantage is that this 
method places more load on the scripts and database; the scripts are run and the 
database is accessed each time a page is requested. 



P1:KPE 

WY022-29 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 




482 Part lv ♦ Advanced Web Authoring 

Database Publishing Case Study— A 
Newsletter 

An online newsletter is a good example to show the power of database publishing. 
Many such documents are online, from daily Web logs to online article repositories. 

For more information on Web logs, see Chapter 30. For many examples of Web 
logs, see the listsatSyndic8.com (www.syndic8.com) or Userland Software 
(www. userland. com). For online article repositories, see any number of Web 
sites provided by lnternet.com (www. i nternet . com). 

The concept is straightforward: take a bunch of small to large articles and present 
them in a logical online format. Make them presentable in various formats (by 
author, by date, by subject, and so on), and include a search feature for users to find 
content that interests them. 

The manual method 

A friend of mine maintained a publishing site before the golden age of Web blogging, 
before the numerous tools were available to aid such efforts. He used a manual 
system of publishing, similar to the following: 

1. Daily articles would be posted at the top of the main page. This would move 
older articles down on the page. 

2. Once a month (usually at the end of the month), the content assembled on the 
main page would be moved to an archive page. The archive would be named 
according to the month it was assembled (for example, ma rch - 04 . html ). 

3. The main page would be cleared of article content, and a link to the new 
archive would be added to the navigation section. 

4. The process would repeat for each month. 
Figure 29-3 shows this process in a graphical format. 

The database method 

After a few months of performing the process outlined in the preceding section, my 
friend related his plight to me and we set to work implementing a database 
publishing system for his use. The system functioned as outlined in the following list: 

1. Using a simple form, each article could be entered into the database. Each 
article was stored with the following data: 

• Date article was written 

• Author of article 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 ♦ Introduction to Database-Driven Web Publishing 483 



Daily Process 











Article 
(Day1) 












Main 
Page 










Article 
(Day 2) 




















~l 
























Article 
(Day 3) 

























Monthly Process 



Add link 
to new 
archive 



Main 
Page 



Move 
Content 



Monthly 

Archive 

Page 



Figure 29-3: The manual process of maintaining an online 
newsletter. 



Subject of article 

Main text of article 

Whether the article is final or in draft form (should it be published?) 



2. The main page of the site used a server-side script to retrieve the last few 
articles from the database and present them in their entirety. 

3. A navigation bar allowed a user to visit monthly archives. The same server-side 
script generated all monthly archives — the month was passed as an argument 
and the script would retrieve only articles published in that month. 

4. A full-text index was generated on each article, allowing a simple search 
function to be implemented for users. The user would enter search terms into a 
simple form — the data entered would be used in a query against the database 
content. Matching articles were presented on a separate page. 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



484 Part lv ♦ Advanced Web Authoring 



v 



T 'P As previously mentioned in this chapter, many Web blogging programs exist 

to easily implement the system described here. However, these programs do 
not alleviate the need for custom server-side scripts. At times, you will need a 
customized system, either to augment an existing system or to replace a prefab 
tool. The concepts presented in this chapter also provide a decent base for 
building other database-enabled Web projects. 



Figure 29-4 shows a graphical example of this new process. 



Web 
page(s) 








Retrieval 
Script(s) 










Database 



Figure 29-4: The new process places the content in a database where 
server-side scripts can retrieve it as necessary. 



The tools 

For this task MySQL was used as the database and PHP was used as the scripting 
language. Both technologies were well known, could be easily implemented on the 
Web server (Apache), and provided enough power and flexibility for the project. 
Also, both technologies were attractively priced — they were free. Because both are 
open source projects, they can be downloaded, installed, and used without the high 
price of other commercial solutions. 

Tip For more information on these technologies, visit their home pages. The MySQL 

home page can be found at www.mysql .com. The PHP home page can be 

y foundatwww.php.net. 

Database structure 

Three MySQL tables were created to hold the article data. The first table, for 
authors, holds the details for various authors allowed to post articles. The second 
table, for categories, allows arbitrary categories to be defined and attached to 
articles. The third table holds the articles themselves. 



Tables 29-1 through 29-3 show the configuration of the tables. 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 4- Introduction to Database-Driven Web Publishing 485 



Table 29-1 
The Authors Table 



Column Definition 



Use 



Idx Integer, auto increment Index for authors 

Name Character field Name of author 

Pwd Character field Password for author (encoded when saved in table) 

Email Character field E-mail address of author 



Table 29-2 
The Categories Table 



Column 


Definition 


Use 


Idx 


Integer, auto increment 


Index for category 


Name 


Character field 


Name of category 


Description 


Character field 


Full description of category 





Table 29-3 
The Article Table 



Column Definition Use 

Idx Integer, auto increment Index for articles 

Date article was written 

Index of category that article should be attached to 

Index of author that wrote article 

Title/headline of the article 

The text of the article 



Pubdate 


Date field 


Cat 


Integer 


Author 


Integer 


Title 


Character field 


Article 


Text field 


Publish 


Integer 



Used as binary field (0 = draft, don't publish; 
1 = final copy, publish) 



The following listing shows the table definitions in MySQL: 

CREATE TABLE 'authols' ( 

'idx' int(10) unsigned NOT NULL auto_i ncrement , 
'name' varchar(40) NOT NULL default ", 
'pwd' varchar(20) NOT NULL default ", 



P1:KPE 

WY022-29 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



486 Part IV ♦ Advanced Web Authoring 



'email' varchar(40) NOT NULL default ", 
PRIMARY KEY ( 'l'dx' ) 
) TYPE=MyISAM ; 

CREATE TABLE 'categories' ( 

'idx' int(10) NOT NULL auto_i ncrement , 

'name' varchar(40) NOT NULL default ", 

'description' text NOT NULL, 

PRIMARY KEY ( 'idx' ) 
) TYPE=MyISAM ; 

CREATE TABLE 'articles' ( 

'idx' int(10) unsigned NOT NULL auto_i ncrement , 

'pubdate' datetime NOT NULL default '0000-00-00 00:00:00', 

'cat' int(10) unsigned NOT NULL default '0', 

'author' int(10) unsigned NOT NULL default '0', 

'title' varchar(80) NOT NULL default ", 

'article' text NOT NULL, 

'publish' tinyint(l) unsigned NOT NULL default '0', 

PRIMARY KEY ( 'idx' ) , 

FULLTEXT KEY 'title' ( ' ti tl e ' , ' a rti cl e ' ) 
) TYPE=MyISAM ; 

Scripting basics 

As mentioned earlier in this section, PHP was chosen for the server-side scripting 
because of its ability to interface easily with MySQL. With the MySQL functionality 
compiled into PHP, opening a database connection is performed with the 

mysql_connect( ) function: 

$ 1 ink = mysql_connect ( "host ", "user", "password") 

The host, user, and password arguments are replaced by the information 
necessary to access the database. In this case, the database is running on the same 
machine as the Web server, solocalhostis used as the host. The user and 
password arguments are replaced by account credentials that have read-only rights 
to the database (the scripts will only retrieve info, not write it). 

After a link has been established to the database, queries can be run against the data 
using the my s q 1 _q u e ry ( ) function: 

$result = mysql_query ( $query , $1 i nk) ; 

In this example, the $q ue ry variable contains the SQL query. The results of the 
query are stored in the $ res ul t variable. The script can then process the results 
and display them accordingly. For example, the following query would return the 
titles of all published articles in the database, sorted by their publication date: 

SELECT title FROM articles WHERE publish = "1" 
ORDER BY pubdate DESC 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 4- Introduction to Database-Driven Web Publishing 487 



What is SQL? 



Structured Query Language (SQL, generally pronounced "sequel") was developed as a means 
to lend consistency to database queries. The language provides keywords to accomplish 
standard database tasks— looking up information, storing information, replacing information, 
and so on. Each command given to the database is called a query, whether it is simply 
querying for information, storing info, or performing some other task. 

Like most computer technologies, SQL varies a bit from implementation to implementation. 
The examples presented here are specific to MySQL and might be different if you are using 
PostgreSQL, Microsoft Access, or other SQL-compatible databases. 

The basic way to look up information is via a SELECT query, in a form similar to the following: 

SELECT datd_list FROM table_l ist WHERE conditions 

For example, to select all customers' first and last names when the customers' address is in 
the 46250 ZIP code, you could use a query similar to the following: 

SELECT first_name, last_name FROM customers 
WHERE zipcode = "46250" 

This, of course, is provided that you have a table named "customers" that stores data in fields 
named first_name, 1 ast_name, and zi pcode. 

Adding data uses a different query, utilizing the INSERT format: 

INSERT INTO tabl e_l ist (data_list) VALUES (data_val ues ) 

For example, to insert a customer's data into the customer table, you might use a query 
similar to the following: 

INSERT INTO customers (first_name, last_name, address, city, 
state, zipcode) VALUES ("T.", "Wi erzbowski " , "Colonial Marine 
Way", "West Hollywood", "CA", "90069"); 

As previously stated, implementations of SQL vary between applications, so you should check 
the documentation for your database server to determine what form of queries to use. 



If this query were used in the preceding my s q 1 _q u e ry ( ) example, the article 
titles would be stored in array form in the $ r e s u 1 1 database. PHP could parse the 
data, outputting one title per line (in HTML format) using code similar to the 
following: 

print "<p> \n"; //Start the text block 

while ($1 ine = mysql_f etch_a rray ( $resul t , MYSQL_ASS0C ) ) { 

// For each returned title, output in italic font 

print "<i>$l i ne [ ' ti tl e ' ]</i ><br> \n"; 



print "</p> \n"; // End text block 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



488 Part lv ♦ Advanced Web Authoring 



The net result of this code would be a listing of the titles of all published articles, 
sorted by their publication date in descending order, similar to the following: 



<i>Bush heads to Africa</iXbr> 

<i>Marvel movie news</i><br> 

<i>Thousands of Web sites might be attacked on Monday</iXbr> 

< i > M i a m i running back re-sentenced</i><br> 

<i>Charlie Chan movies banned in the USA</iXbr> 

<i>Riddick name change and new release date</i><br> 

</p> 

Sample scripts 

By using methods similar to those described in the previous section, you can create 
several scripts, each of which can access the database of articles and provide the 
data in various forms. Some examples follow: 

♦ Headlines (the title field) of the last two weeks of articles (see Figure 29-5). 

♦ Articles sorted by category (see Figure 29-6). 



! Iittp: 192.168.70.30 Iitml3e hen<llines.|)h|) - Miciosoft Internet Explorei 



BiJ^ 



File Edit View Favorites Tools Hel|> 



a 



o ' o - a n ® p -itfolQ'&s-a 



Address 



] http : // 1 92 . 1 63 . 70 . 30/html3e/headlines . php 



HB' 



Miami running back re-sentenced 

Charlie Chan movies banned in the USA 

Marvel movie news 

Riddickname change and new release date 

Bush heads to Africa 

Thousands of Web sites might be attacked on Monday 



$ Internet 



Figure 29-5: The headline script generates headlines from recent articles. 



P1:KPE 

WY022-29 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 ♦ Introduction to Database-Driven Web Publishing 489 



) http://192.168.70.30' , lilml3e-'cate<)oiies.pli|> - Microsoft Internet Explorer 



File Edit View Favorites Tools Help 

a - o - a a ft p**® 



0- a 



... , http://192.168.70.30/html3e/categoites,php 



Category: Football 



Category: News 



SBB 



3H Go 



Miami running back re- 


sentenced (Posted by Tom on 03-01 


-2004 03:03) 


Category: Movies 


Charlie Chan mo vie s b anne d in the US A (P o ste d by Rolf on 
Marvel movie news (Posted bv Rolf on 03-02-2004 08:031 
Riddick name change and new release date (Posted by Rolf 


02-29-2004 06:02) 
in 02-28-2004 18:02) 



Bush heads to Africa (Posted bv Geoff on 03-03-2004 13:03) 

Thousands of Web sites might be attacked on Monday (Posted by Geoff on 03-01-2004 23:03) 



$ Internet 



Figure 29-6: The category script generates recent article headlines sorted into 
their respective categories. 



♦ Teasers of current articles — that is, the first 20 words of the article (see 
Figure 29-7). 

♦ Full text of the article with links to more articles in the category or by the 
author (see Figure 29-8). 

In addition to the standard data, the scripts also provide links to additional 
information. For example, the headline script outputs the headlines embedded in 
links to the full article script, similar to the following: 

<a href="di spl ayarti cl e . php?i dx=20"> Charlie Chan movies 
banned in the USA</a> 

When a user clicks the headline, the displayarticle script is called to display the 
full article. Similar constructs can be used to link to more articles in the same 
category, by the same author, and so forth. 

The scripts can be included in template pages via server-side includes, or the entire 
site can be generated via PHP, and the article scripts can be called as required. 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



490 Part lv ♦ Advanced Web Authoring 



Tip 



^ http:>"192.1G8J0.30/html3e/teasers.php - Microsoft Internet Explorer 



- 1 ;K 



File Edit View Favorites Tools Help 



l! 



a b -a 



Address g) http://192.168.70.30/html3e/teasers.php 



Bt 



Charlie Chan movies banned in the USA 

Ok not banned exactly but a season of classic Charlie Chan mystery movies has been pulled from 
US TV... [ more l 

Marvel movie news 

Look for the first trailer from the Spider-Man sequel in November. 

According to Variety, Sony will handle international distribution ... [ more l 

Riddick name change ami new release date 

The Chronicles of Biddick lost the T, C and O and is just Biddich again. Biddich has moved 
up ... [ more l 

Bnsh heads to Africa 

Monday President Bush heads to Africa in a hope to promote his administration's war on AIDS. 
Pres Bush wants ... [ more l 

Thousands of Web sites might be attacked on Monday 



- 



a 



Figure 29-7: The teaser script generates short versions of articles. 

Adding search capabilities 

Adding a search capability to the system is remarkably easy. A full-text index is 
created on the title and arti cl e columns in the arti cl e table (see the MySQL 
table definition earlier in this section). This index can then be searched using textual 
expressions via a select query, driven by user input into a standard HTML form. 
Articles that match the search criteria are then displayed (generally in headline 
form), and the user can browse them accordingly. 

Even without a full-text index the database can be easily searched via a WHERE 
-^ clause in a SELECT query. For example, to find all articles that contain the text 
' "Charlie Chan," a query similar to the following could be used: 

SELECT idx, title, article FROM articles 
WHERE title LIKE "%Charlie ChaniT 
OR article LIKE "^Charlie Chan?" 

This query would return all articles that contained "Charlie Chan" in their title or in 
the text of the article. 



The other-side of the process— publishing tools 

One area that has not been covered in this case study is the publishing side, that is, 
how do the articles get into the database to begin with? This process requires a few 



P1:KPE 
WY022-29 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 4- Introduction to Database-Driven Web Publishing 491 



hltp: "192.1 68.70 .30.'htiiil3e.'displayarticle.prip?idx=11 - Microsoft Internet Explorer 
File Edit View Favorites Tools Help 



BBS 



http : // 1 92 . 1 68 . 70 . 30/html3e/displayartide . php?idx= 1 1 



"E1B' 



Ridditk name change and new release date 

Ported l>y: EoK cm 02-28-2004 li 18:02 

The Chronicles ofPiddick lost the T, C and O and is just Piddick again. Piddick has moved up 
two weeks, now set to hit the wide screen on June 11, 2004 - a week after Harry Potter J, and a 
week before Shrek 2. Tins could indicate an 'R' rating as an alternative for the PG bookends. 

Category: 



Note 



Figure 29-8: The full-text script generates the full text of an article. 

additional scripts, accessible only to the authors and system administrators. The 
scripts allow for creation of new author records, new categories, and new articles. 
For security's sake, only the new article script is accessible to authors — system 
administrators take care of the creation of new authors and new categories. 

As a temporary measure, tools such as phpMyAdmin can be used to manipulate 
the data in a MySQL database. Figure 29-9 shows an example of phpMyAdmin 
in use. (You can find more information on phpMyAdmin at www . phpmyadmi n 
.net/.) However, the tool is somewhat archaic in design and can be easily 
misused, at worst resulting in massive data loss due to a misplaced click. It's 
usually best to create more user-friendly tools. 

An example of an article maintenance tool is shown in Figure 29-10. 



Authentication and Security 



Any additional technologies added to Web publishing bring additional security 
concerns — database publishing is no exception. You need to be concerned with 
when adding a database to the mix: access to the database as a whole and further 
restricting access for users. 



P1:KPE 

WY022-29 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



492 Part lv ♦ Advanced Web Authoring 



|j 1 1 \-<i'j<*.t. jr^ij o i i*^ iniiiiiiHi i>n 1 ■:• c .i 1 ln>tt -|fh|>MyAi liniii I.'l.'i - Mi •: i 


"■soft Inteiner Lxplvi^i 


QEQ 


Hie LI it Ifiew Kivorites look Help 




. 


8'0'iat ( Pfc*#|o*!»S< 



^.-j htizi.'.'L-?^ L6i.'D.iO|ft)hpTi i cdTlrvl-(fc:<.i 



Home 

i! ifllpnr^r 1.1 
B n=dia f2> 

s iuhw^ (it; 
13 fl.-tif.fti 



■^ 



Database pufcsys - table categar/es running on localhost 

I Brows* ' "' Setort ] \ In wit | [ Empty | | [nop | 





Held 


lype 


AttrihirtetHi 


1 Uata 


i It Latra 


j n LC-ti Crll 






n 


::< 


i-i;il; 


he 




■au:o_nc lenient f.Tantje L'rcp H 


" = ry Index 


.Iniqu? 


u 1e:d 


n 


:rc 


vntr.hn'f'i-l 


kr 




Changn Rrrp Pi 


Try Inrinv 


Jniqii"! 


=ii irrt 


n 


e e n r 1 1 :■ b i m 1 1 


te>:: 


fit 




f.Tantje L'rcp H 


" = ry Index 


.h'siiiuv 


u 1e:d 



I '-•'■»" I Or [ >"P I 



lnde>:? e Docume":=: on] 

P.eynamg lype -.' «i ■ I i 1 1 .ility Action H*M 

PRIMARY PRIMAR V 3 CrcpEJ! d:< 



Hmr^ =' nHftv nn 1 



M 



£ I ■ il <m :■ 1 1 i .; v'nil Li u 
Fnnrifr dy-amir: 

Viral ?,134 ^vrnn Row nngrh « ^Ifi 

Row =ize o 7II D^te* 
NujdA.kinduj. ^ 



i^.y uyygy . 

r.=i= iif =m 

I r i • J 



■ F_r 3£_ (ueiVqueiiEE :n databai? i.bivi fCicumentatb 
S ELECT " FR OM 'ualuuu -i = t ' W- ERE 1 _ 



3howlhis que\ i= = =t|ain 
r>l_o:=: on of the te>::r"le : 



< 



- 



i>i 



£ li.=n*L 



Figure 29-9: Tools such as phpMyAdmin, although not very user-friendly, can help fill 
gaps in database administration. 



bit fifln xiaw §o gpttnuiu it-m itfinsow tJHp 






ji - _ ** . - _3» , A rmpj , /Toi:.air.siVjr!:iephp 


l*llrf.*«ftl 


« - 






[ ^Hofflt 40«*mirtj ^fiidHjdJrvc. ./flpl Hil Hfttnrt .J$upmt JShop JPro«i«i ^Trimma 




fori* 20Q3-OT4?Ol:t7 
Integer?; 1 rwrrfn*JJ ;| 
Author: | citnrr ^J 






Subjwt: |" 
Artlirlr: 


Add | Rn-iirf | CtflCfl | 

BoitfUn | fioMOf | BalOn | rtalOfl | UJiflOn | UnsOff | 
L-nefiita). ] PmBnA | HoraLlrw \ 




URL Description: | 


URL; 

Reminder: Dc* rvM forget to tdd the protocol (te. "heipi/A 'ratdko:'. etc) to the URL ! 

AdWUflt | 






..i, ^^ / £l rjuLUl-.L-M D^IL' (A i 8 il-LlI 


1 


l-H*- 



Figure 29-10: An example of an article maintenance tool that allows creation 
and editing of articles in the database 



P1:KPE 

WY022-29 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



Chapter 29 4- Introduction to Database-Driven Web Publishing 493 



In the case of MySQL, access is restricted per user, as seen in the user and password 
fields required in the mysql_connect( ) PHP function. Each user is assigned unique 
rights to the data. Access can be granted or denied on a table-by-table basis. 

For a publishing system it is best to create a very limited user for general use. This 
user can be used by the scripts for general query access, but have write, delete, and 
update access denied. This helps limit the exposure of the data; even if the general 
user credentials are compromised, the data can only be queried, not overwritten or 
deleted. 

For authors you could implement a tiered security structure as follows: 

♦ Protect the maintenance scripts by placing them in an area of the Web site that 
is only accessible by machines used by the authors or, better yet, is 
password-protected by the Web server. 

♦ Use a unique user account (author) for author-level database access, granting 
permission to the a rti cl e database but restricting access to the categories 
and authors tables. 

♦ Use the authors table to uniquely identify each author, requiring the 
author(s) to log in using the credentials stored in the table. Additional code in 
the article maintenance script(s) can restrict authors from modifying articles 
that are not their own. 

Note A unique MySQL account for each author might be overkill. It adds additional 

database administrator overhead while only providing slight advantages. You 
wouldn't want to restrict individual rows in the database by author; simple 
script-employed, individual article security is enough. 



Summary 



Database publishing has been around for many years. However, only in the last few 
years have economical, easy-to-use tools been available to help deploy 
database-driven solutions. This chapter introduced you to the concept of database 
publishing and showed you an example of how database integration can be used to 
add dynamic content to your documents. 



P1:KPE 

WY022-29 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 16, 2004 2:57 



494 



P1:KTX 
WY022-30 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



Creating a 
Weblog 



The Web has created a viable media for publishing all 
manner of content — providing an alternative avenue for 
businesses and the average Joe alike to propagate information. 
A recent innovation, weblogging, extends the ability to publish 
content online and to even syndicate the content. This chapter 
covers the basics of blogging. 



The Blog Phenomenon 



Weblogging, or blogging for short, is the latest craze on the 
Web. Gaining popularity in the mid-90s, almost everyone has a 
blog nowadays. 

Blogs come in many varieties: 

♦ The equivalent of an online diary, where the owner posts 
their thoughts about life, the universe, and everything 

♦ Themed articles where the owner posts their thoughts on 
specific topics, such as technology, politics, religion, and 
so on 

♦ News-related blogs where the owner posts aggregated news 
content 

However, just like the desktop publishing explosion in the 
late '80s taught us, just because someone can access 
technology doesn't mean they should. As desktop publishing 
came of age, everyone with a computer began fancying 
themselves as a designer — it became quite clear that graphic 
design is an art that can only be aided, not replaced, by 
technology. Now, as blogging is reaching epic proportions, 
many people fancy themselves as Dave Barry-caliber writers 
seemingly with the assumption that the entire world cares 
what they think. It only takes a few moments of surfing the vast 
variety of blogs to ascertain just how wrong those 
assumptions can be. 







♦ ♦ ♦ ♦ 
In This Chapter 

The Blog Phenomenon 

Blog Providers and 
Software 

Posting Content to Your 
Blog " 

Handling Comments 

Using Permalinks 

Using Trackbacks 

Syndicating Content with 
RSS 

Building an Audience 

♦ ♦ ♦ ♦ 




495 



P1:KTX 

WY022-30 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



496 Part IV ♦ Advanced Web Authoring 



Note Dave Barry is a well-known humor columnist for the Miami Hera Id. His column 

is syndicated in over 500 newspapers worldwide. Dave Barry actually has his 
own blog, which can be found at http://weblog. herald. com/column/ 
da veba my/. 

That said, the blog world is full of useful information. From offering a look at the 
daily routine of people in interesting positions to the latest electronic gadget news, 
several blogs are bound to interest even the most jaded reader. 

Note The support that large corporations (such as Microsoft) are lending to blogging 

is a sign that blogging has come into its own and is seen as a valuable resource. 
Such corporations encourage their employees to blog with the intent that such 
activities will increase communication between employees and the tech world 
at large. However, in the wake of such support also come a handful of blog- 
related firings, companies letting employees go for inappropriate blog entries. 

The real power of blogging comes in the community that has grown up around the 
technology. Online blogs have created a tightly knit subculture on the Web where 
authors read and respond to each other's articles, leave comments to articles of 
interest, and so forth. 

Note The ability to leave comments on an author's blog is a double-edged sword. 

Although the feature allows the community to be more involved, the feature 
has also been used inappropriately by the spamming community. Anonymous 
comments containing links to other sites routinely get indexed by search en- 
gines. As such, comments on popular blogs can cause the site referenced in the 
comment to increase in rank in the search engine. Several tools are available 
to help stop blog spamming, but just like e-mail spam, nothing will completely 
remove it. 

Another complementary technology, "Really Simple Syndication" (RSS) feeds, has 
helped the aggregation of blog content. RSS is an XML specification for syndicating 
content. It enables authors to publish their headlines or teasers for articles in a 
distinct format — a format that can then be read by other applications to effectively 
syndicate the articles. 

Note Look for more information on RSS in the section, Syndicating content with RSS, 

later in this chapter. 



Blog Providers and Software 



Just as there are many topics for blog content, there are many blog providers and 
software to enable blogging. This section gives an overview of the more popular 
blogging provider/software solutions. 



P1:KTX 

WY022-30 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



Chapter 30 ♦ Creating a Weblog 497 



Userland Software 

According to the Userland Software site, Userland "provides Web Content 
Management and creation tools for building sites that bring people together." One of 
the pioneers of blog technology, Userland provides several different content 
management and blog solutions. 



' 



Note You can find Userland Software on the Web at: www . userl and . com/. 



Offered as commercial products, Userland Software's Manila and Radio Userland 
tools enable users to easily set up content management and aggregation sites. 
Manila is geared towards workgroups whose members need to share information. 
Radio Userland is geared toward the general blog author. 

The benefit to using Userland's tools is twofold: 

♦ The tools integrate into your local system, easing the pain of setting up online 
solutions or using Web-based solutions. 

♦ Userland has built a large blogging community; using their tools connects your 
site to this community. 



Movable Type 



One of the most popular server-side blogging applications is Movable Type. Movable 
Type uses a series of CGI programs to publish and maintain blog content. Movable Type 
must be installed on a server that has Perl and either a Berkeley DB or MySQL database. 



- 



Note You can find Movable Type's Web site at: www. movabl etype . org/. 



Movable Type is a very popular solution due to the following: 

♦ Movable Type is highly customizable, using a flexible template system to easily 
publish content in a variety of formats and/or integrate into an existing site 
design. 

♦ The large community of developers creating various plug-ins to extend the 
capabilities of Movable Type. 

♦ The large community of bloggers who use the program. 

♦ Its relative low cost (free for non-commercial use, though donations are 
encouraged, and $150 for commercial use license). 

Movable Type uses special tags that you can embed in any HTML document to 
publish your content. Although Movable Type is fairly easy to install and use, it is 
recommended for the more technical user. 



P1:KTX 

WY022-30 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



498 Part lv ♦ Advanced Web Authoring 



Blosxom 

Blosxom (pronounced "blossom") was designed as a lightweight, feature-packed, 
blogging application. One of the more simple solutions for blogging, Blosxom runs as 
Perl CGI scripts on a variety of platforms. Using simple text files for article storage, 
Blosxom is designed to work with the tools you are already using — Emacs, Microsoft 
Word, Notepad, or other text editors. 



- 



Note Find the Blosxom Web page at www. bl osxom. com/. 



Blosxom is completely Open Source, meaning that it is free for use and the source 
code is available for you to modify as you want or need. Blosxom also has a fairly 
robust plug-in architecture and an active developer community providing several 
plug-ins. 

Although its simplicity is also its bane, Blosxom is a good middle ground between 
the other two solutions mentioned in this section. 



Posting Content to Your Blog 



Posting content to your blog is usually as easy as typing an article into the blogging 
application you are using. In the case of Radio Userland, you use their application; 
Movable Type uses Web based forms; and Blosxom uses any text editor. 

Blog content varies from blog to blog and article to article, but content generally falls 
into one of the following categories: 

♦ Generalized, original content 

♦ Response to another online article or item 

♦ Aggregation of information from elsewhere 

In most cases, your content will contain a link to other content online or even text 
from the content. For example, the following is typical of a blog entry: 

In his Things I Hate column, Joe User makes the following observation: 
"This would be text from the column referenced above ..." 
My feelings on this matter . . . (response to above citation here) 

In this example the text "Things I Hate" would be a link to the article being cited. The 
verbatim text is set off in quotes or uses a distinct convention to identify the text as 
a quote, not the citing author's work. The text then continues with the current 
author's text, adding to the cited article, offering a retort, or whatever. 



P1:KTX 
WY022-30 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



Chapter 30 ♦ Creating a Weblog 499 



T 'P Although quoting others is a huge part of the whole blog scene, it is still very 

important to clearly delimit and credit other people's text. In most cases, you 
y will want to indent the text, set it off in quotes or a special font, and make sure 
to include a link to the original. 



Handling Comments 



Most blogs also include a comment section that appears directly after the posted 
content. Visitors to the blog are encouraged to post comments about the articles 
posted there, creating the hybrid news article-public forum scheme that is a blog. 

Most blogging applications support comments and allow you to configure how the 
comments are presented in your blog. One of the choices you will need to make is 
how comments are represented on your page — whether they are displayed whenever 
the attached article is displayed, or only available when a comment link is clicked. 

Although most visitors understand the purpose of comments in a blog, there are still 
people who abuse the comments, using them to attack others, post inappropriate 
content, and so forth. 



Note 



Thankfully, most blogging software has tools to help stop comment spam and 
control user posts. Check the documentation for your blogging software to 
determine what tools are at your disposal for displaying and managing comments. 

Keep in mind that expressing one's views is part of the appeal of blogs. As such, 
you should be prepared for negativity and even direct criticism if you enable 
comments. You should resist the urge to delete comments you simply disagree 
with— but stay on top of content that is truly objectionable to help protect your- 
self and readers. Alternatively, you can disable comments altogether. 



Using Permalinks 



Most blogs include several methods to browse their content: 

♦ The most recent articles are posted in descending order on the main page. 

♦ Search features enable users to find articles containing content that interests 
them. 

♦ Archives list articles by day, week, or month and have controls to move from 
article to article. 



The advantage to having multiple methods of displaying content is that visitors to 
the site can choose the method that best suits their needs. However, other blog 
authors need one location to reference an article when linking to it from their 
site/blog. Enter the concept of permalinks, a unique URL that points directly to the 



P1:KTX 
WY022-30 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



500 Part lv ♦ Advanced Web Authoring 



article in question, usually on a page all by itself (without being buried in a 
navigation scheme). 

You will typically see permalinks near the bottom of the text of blog articles, as 
shown in Figure 30-1. 



^J PunchtheBag - Microsoft Internet Explorer 



Filo Erfit View Favorites TdoJs Help 



g-o-e a *>>**« 



a m a 



Address |^htr.p:o>w^,pund-r.hgbag com/ 



& 



Tight, Fich: , fight, " '. ye led. 

Wei ro: to be. Daniels and the guy. who was a Democrat precinct 
corrrnitteeman, stuck up a friandly conversation like two atnletas 
after 3 game and the moment for ckc torrent was smothered. 

I normally jump on the bardwagon for anything gimmicky to attract a 
largar voter pool, tu: the bottom lire is the campaign needs to do the 
old fashioned nuts and bolts of identifying favorable voters by pouring 
thrcugh voter nane ists, raising money, and buying targeted TV and 
radii =iris. 

I don't :hnk RealtyMit^h is a :argeted approach to attracting VDters 
and the money would be bettor spent en traditional acver:ising in 
October that voters say they hate, bjt tie 30-second ads are still 
effective. 

Truth is, a ::cineback tour fea:uhng The Partricge Family chss-cmssirg 
the sta:e in their schoDl bus would generate mora enthusiasm than 
Rea it/Mitch. 

Posted by: PurchTheBag ^ 

March 10, 2004 01:^0 PM — " 



Dick Morris Anti-Kerry Strategy 



m= 



Totally 1 ruthless. 

Pnstprl hv PnrrhThpRpn 



_> Internet 



permalink 

Figure 30-1 : Permalinks, usually located near the end of articles, provide a unique URL 
to reference the article. 

Sometimes blog authors use the verbatim text "permalink" to denote the location of 
the permalink. Other blogs, such as the example shown in Figure 30-1, note the link 
with a graphic or simple "link" text. 

Whenever you link to another blog's content, be sure to use the permalink. 



Using Trackbacks 



You have seen how links are used to reference articles elsewhere, but how does the 
original author know about the link to his material? That dilemma was one of the 
reasons behind the invention and adoption of trackback technology. 



P1:KTX 
WY022-30 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



Chapter 30 ♦ Creating a Weblog 50 1 



TrackBack was first released as an open specification in 2002. It was released as a 
protocol and feature of Movable Type version 2.2 and has since been adopted by 
many other blogging applications. 

The methodology behind trackbacks is shown in Figure 30-2. Site A posts an article 
that is interesting to Site B. Site B references the article on Site A and uses a 
trackback to let Site A know about the reference. Site B also uses trackbacks to alert 
other sites that may be interested in the topic — whether the interest is in the original 
article or the reference. 



Site A 




SiteB 


Article 


Ref. 





Other 

Interested 

Sites 



TrackBack 



Figure 30-2: The methodology behind trackbacks. 



Syndicating Content with RSS 



Note 



Netscape introduced RSS in 1999 as a concept to syndicate content. At that time, RSS 
stood for Rich Site Summary. However, Netscape abandoned the concept in 2001 and 
UserLand Software began pioneering a similar technology as Really Simple 
Syndication. Still others refer to the RSS concept as RDF Site Summary. 

In any case, RSS exists as a simple way to syndicate content. 

UserLand Software maintains quite a bit of documentation on RSS at the 
following Web site: http://backend.user! and. com/rss. 



Syndication is a means of distributing content with the intent of allowing others to 
publish it. Typically, syndication applies to newspaper columns, comics, and other 
works of art — and, generally, one derives a fee for each use. 

In this case, syndication means an easy method for others to preview your content 
and optionally republish it. Sites such as si ashdot . org, cnet . com, and others use 
RSS feeds to syndicate their content, as do many Weblog (blog) authors. 



P1:KTX 

WY022-30 WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



502 Part lv ♦ Advanced Web Authoring 



RSS syntax 

The syntax for RSS feeds varies considerably depending on the version of RSS that 
you adhere to. However, the feed is usually published as an XML file with a strict 
syntax. For example, a typical RSS feed file might resemble the following: 

<?xml versi on="l . 0"?> 

<rss versi on="2 . 0"> 

<channel > 

<title>t7't/e_of_s7'te</title> 

<descri pti on>descri pti on_of_s i te</descri pti on> 

<1 ink>/7ttp:// / / nk. to. s i te</l ink) 

<i tem> 

< t i 1 1 e > 1 7 tle_of_ art i c 7 e < / 1 i tie) 

<descri pti on>short_desc_of_arti cl e . . .</description> 

<pu b Da te> pubdate_ i n_RFC 8ZZ_f or ma til pub Date) 

<1 i nk> 7 in k_to_art i c7e</l i nk> 

</item> 

<i tem) 

</item> 

</channel > 
</rss> 

In XML format, the file's headers spell out its content and which version of RSS is 
being used. The beginning of the <channel > section provides details about the main 
site, while each < i tem> section provides details about a particular article. Each feed 
can have up to 15 <i tem>s and is generally arranged with the newest article first 
and the oldest article last. As articles are added to the feed, the older articles are 
moved off the feed. 



Publishing the feed 



The XML file is made accessible via HTTP, and special applications can access the 
feeds and notify users when the feed is updated. For example, the open source 
project BottomFeeder can monitor several feeds and even seek out new feeds. 
Figure 30-3 shows an example of BottomFeeder in action. 

Note You can download BottomFeeder from the BottomFeeder home page at 

www. cincomsmall talk. com/Bottom Feeder/. 

A popular Windows reader is NewsGator (http : //www. newsgator.com/), which 
integrates into Microsoft Outlook. Several other applications can monitor RSS feeds 
as well, such as Trillian (www. tri 1 1 i an . cc/tri 1 1 i an/i ndex. html). (The Pro 
version has a nifty news plug-in.) 

These tools monitor feeds by periodically accessing the RSS feed file and informing the 
user when the feed file changes. The individual <i tem> blocks are usually displayed 
for users, who can visit the site or see the complete article by clicking the listing. 



P1:KTX 
WY022-30 



WY022/Pfaffenberger WY022/Pfaffenberger-v3.cls June 12, 2004 19:35 



Chapter 30 ♦ Creating a Weblog 503 



feWiBHUHIHl 



file System Browse Search Network View RJugins Help 




J, 3ubs^'i3:ions (-T/4) 
f-p CNET Ne^s.coin 
!--J] lai Murdoch w?3 
;-|§| Rolfs MDv'e '■■Jew; 

^ "eed Lis:s iC/Ti 




l£te 



C3 2:37 /*M 

C3 2:37 £M 

M.3 y:ia HM 

.'-U y:ia HM 

ra Riri pm 

C 3 9:^8 PM 
C 3 9.^0 PM 
C 3 9:^8 PM 
C 3 9:^3 PM 
C 3 9:^8 PM 



Iten Tille 



| lt3H Cater. A 



Hardware Based Commute Map Gadget. 

FtFID Industry Confidential Memos 

Massachusetts Proriinrj Microsoft Settlement f.inpes 

Michigan's Proposed Spam Law Called loucfhost In U 

TvK^'i An Old Athhi N-fw — rirts 

3LJi CiauiL Cuurt Finds 'TTiujiiinnHiliriy Fair Use 

Trustworthy Software For Tlie N3A? 

SCO Taking Linux Discussion To Japan 

Distributed Computing economics 

Frccncl Creator Debates RIM 



r: 



http ://s las hdot.orgy'article.pl ?s id -0 3/0 7/D7/2 2 19 2 16 



^'1 1 i.fr?Tfi In l=F Tilnutqs 



Figure 30-3: Applications such as BottomFeeder can monitor several RSS 
feeds. 



Note 



Most blogging software will automatically create RSS feeds from your content. You 
still must configure how many articles will be placed in the RSS file, how long they 
will stay, and what information (title, teaser, and so on) is stored in the feed. See your 
software's documentation for details on how to configure your feed. 

If your blogging software doesn't support RSS feeds natively, look for tools such as 
NewsIsFree (http : //www. newsi sf ree . com/) to buil